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?
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.
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.
精彩评论