views:

360

answers:

3

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.

+3  A: 

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]
Mark Cidade
+2  A: 

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.

nickd
+1  A: 

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]
Michiel Borkent