Passing method references to high-order functions

I would like to pass a reference to a method once the object has been instanciated to a high-order function as an argument, but it seems not supported, right? Example:
@value
struct Foo:
fn func(self) -> Int:
return 42

# None of these declarations work:
fn high_order_func(f: fn (Foo) -> Int) -> Int:
# fn high_order_func(f: fn () -> Int) -> Int:
return f()

fn main() -> Int:
foo = Foo()
print(high_order_func(foo.func))
@value
struct Foo:
fn func(self) -> Int:
return 42

# None of these declarations work:
fn high_order_func(f: fn (Foo) -> Int) -> Int:
# fn high_order_func(f: fn () -> Int) -> Int:
return f()

fn main() -> Int:
foo = Foo()
print(high_order_func(foo.func))
4 Replies
Manuel Saelices
Manuel SaelicesOP4w ago
The error I receive is something like this:
error: invalid call to 'high_order_func': argument #0 cannot be converted from unknown overload to an instance of 'fn(Foo) -> Int'; did you mean to instantiate 'fn(Foo) -> Int'?
print(high_order_func(foo.func))
~~~~~~~~~~~~~~~^~~~~~~~~~
error: invalid call to 'high_order_func': argument #0 cannot be converted from unknown overload to an instance of 'fn(Foo) -> Int'; did you mean to instantiate 'fn(Foo) -> Int'?
print(high_order_func(foo.func))
~~~~~~~~~~~~~~~^~~~~~~~~~
The alternative fn() -> Int definition of the function param, instead of the fn(Foo) -> Int one does not work either. Note that comptime, meaning, passing the function as a parameter instead of an argument, is not possible here as we need to instantiate the Foo object
Darkmatter
Darkmatter4w ago
Can’t you reference it as Foo.func and have comptime.
rd4com
rd4com3w ago
Hello @Manuel Saelices, here is an example with parameters:
@value
struct Foo:
fn myfunc(self) -> Int:
return 42

# Note: capturing [_] for lifetimes/origin !
fn high_order_func[f: fn () capturing [_] -> Int]() -> Int:
return f()

fn main():
foo = Foo()

@parameter
fn foo_myfunc() -> Int:
return foo.myfunc()

#__type_of(foo).__del__(foo^)
print(high_order_func[foo_myfunc]())
@value
struct Foo:
fn myfunc(self) -> Int:
return 42

# Note: capturing [_] for lifetimes/origin !
fn high_order_func[f: fn () capturing [_] -> Int]() -> Int:
return f()

fn main():
foo = Foo()

@parameter
fn foo_myfunc() -> Int:
return foo.myfunc()

#__type_of(foo).__del__(foo^)
print(high_order_func[foo_myfunc]())
Manuel Saelices
Manuel SaelicesOP3w ago
Wow! Good trick!
Want results from more Discord servers?
Add your server