ygejaq
Last Updated: February 25, 2016
·
625
· caseykramer

Delay function evaluation in F#

f#

I've found times when I would perfer to pass in a function "by name" rather than have it evaluated...unfortunately since F# is eagerly evaluated you can't do this without wrapping things in a (fun () -> myFunction arg1) kind of construct. I don't particularly like that syntax, but the following seems much more pleasant:

let inline delayed f a= fun () -> f(a)

You can now use:

delayed myFunction arg1

Things get a little uglier with more arguments

delayed (myFunction arg1 arg2 arg3) arg4

But you could also create an operator which makes it a little less funky

let (<?) f a = delayed f a

And then you could use

myFunction arg1 arg2 arg3 <? arg4