Nutel
Nutel

Reputation: 2294

Short way to pass zero-arity lambda function in OCaml

Is there any short way to pass zero-arity function to another function. For now I do it like this:

let f a b c = ...;;
a (fun () -> f a b c)

Is there any syntactic sugar for the second line?

Upvotes: 6

Views: 831

Answers (2)

Pascal Cuoq
Pascal Cuoq

Reputation: 80276

How about:

lazy (f a b c)

To "apply", use Lazy.force, as in:

# let l = lazy (2+2) ;;
val l : int lazy_t = <lazy>
# Lazy.force l ;;
- : int = 4

The meaning is not exactly the same as (fun () -> ...) and ... () and it's not really shorter. Perhaps if you really need to have a convenient syntax for either lazy or fun () -> you should use a camlp{4,5} extension to that purpose.

Upvotes: 10

sepp2k
sepp2k

Reputation: 370112

If f were defined as f a b c () = ..., you could just do a (f a b c), but other than that no, there's no shorter way.

If you want to you can define the function const like this:

let const x _ = x

And then use it like this:

a (const (f a b c))

But that's not really much shorter (or clearer) than using fun. Also it evaluates f a b c immediately, which is probably not what you want anyway.

PS: The pedant in me needs to point out that (fun () -> ...) is a unary function and there are no zero-arity functions in ocaml.

Upvotes: 6

Related Questions