Reputation: 529
Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like
foo(fun x -> x ** 3)
More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.
Upvotes: 10
Views: 6172
Reputation: 34790
Passing a lambda function to another function works like this:
Suppose we have a trivial function of our own as follows:
let functionThatTakesaFunctionAndAList f l = List.map f l
Now you can pass a lambda function and a list to it:
functionThatTakesaFunctionAndAList (fun x -> x ** 3.0) [1.0;2.0;3.0]
Inside our own function functionThatTakesaFunctionAndAList
you can just refer to the lambda function as f
because you called your first parameter f
.
The result of the function call is of course:
float list = [1.0; 8.0; 27.0]
Upvotes: 3
Reputation: 4011
Functions are first class citizens in F#. You can therefore pass them around just like you want to.
If you have a function like this:
let myFunction f =
f 1 2 3
and f is function then the return value of myFunction is f applied to 1,2 and 3.
Upvotes: 3
Reputation: 99957
Yes, it is possible. The manual has this example:
> List.map (fun x -> x % 2 = 0) [1 .. 5];;
val it : bool list
= [false; true; false; true; false]
Upvotes: 8