Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to pass zero-arity lambda function in OCaml

Tags:

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?

like image 597
Nutel Avatar asked Dec 18 '10 19:12

Nutel


2 Answers

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.

like image 196
Pascal Cuoq Avatar answered Nov 08 '22 23:11

Pascal Cuoq


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.

like image 20
sepp2k Avatar answered Nov 09 '22 00:11

sepp2k