I am looking for a way to define Parameterless lambda expressions in F#, much like the following C# example.
var task = () => {
int x = 3;
DoSomething(x);
}
I tried the following
let task = fun _ ->
let x = 3
doSomething x
It compiles but it gives me task : ('a -> unit)
what I am actually looking for is task : (unit -> unit)
The MSDN Documentation does not talk about this. What am I missing here ?
it's just
let task = fun () -> // whatever you need
you example would be:
let task = fun () ->
let x = 3
DoSomething(3)
assuming DoSomething
is of type int -> unit
- if it returns something else you need
let task = fun () ->
let x = 3
DoSomething(3) |> ignore
to get type unit -> unit
Remark:
Usually you don't write let task = fun () -> ...
but just let task() = ...
The thing you missed:
if you write fun _ -> ()
you are saying you want to take some parameter that you don't mind about - so F# will take the most general (being named 'a
here) - this would include unit
!
()
is the only value of type unit
(more or less void
from C# ... but a true type in F#)