cutlass icon indicating copy to clipboard operation
cutlass copied to clipboard

Ideas for `self` functions

Open vbrandl opened this issue 5 years ago • 3 comments

Do you have any ideas on how to curry functions taking self as a parameter? I thought about keeping the first two arguments together so it looks like this:

struct Foo(i32);
impl Foo {
  fn add(&self, x: i32, y: i32, z: i32) -> i32 {
    self.0 + x + y +z
  }
}

self.add(1)(2)(3)

I tried something like that but ran into lifetime issues and stopped experimenting before asking for you opinion.

vbrandl avatar May 12 '20 16:05 vbrandl

Like other variables, I think we would have to take ownership of self, and return a new Self, so the function could look something like:

fn add(self, x: u32, y: u32, z: u32) -> Self {
    // stuff here
}

and maybe use it with:

let s: Foo = Foo { 0: 5 };
let p = Foo::add(s)(3)(4)(5)

I haven't tried any of this, but I am certain about taking ownership and returning Self. OOP and currying definitely don't go well together :p

oppiliappan avatar May 13 '20 14:05 oppiliappan

I think returning Self is no requirement. The function can return anything but a reference. Returning ownership for any value should work

vbrandl avatar May 13 '20 14:05 vbrandl

Ah sorry, you're right, I suppose I was thinking of transforming the original object via a method.

Any curried struct method would consume the original object, and I can't seem to think of a way to elude that.

oppiliappan avatar May 13 '20 16:05 oppiliappan