ocaml

How to make sense of "let () ="


In OCaml, how to make sense of a definition like:

let () = print_endline "hello world"

Let-definitions in ocaml should look like let x = e but above () is not a variable. So what happens there?

I think it would make more sense to write:

let _:unit = print_endline "hello world"

Solution

  • The syntax for let bindings is "pattern = expression`. Most often the pattern will be a variable name, a wildcard or a tuple pattern of those, but every kind of pattern is valid (as long as the pattern has the same type as the expression).

    The semantics are that the expression will be matched against the pattern and if the match succeeds, the variables bound by the pattern (if any) will be bound during the let's scope. If it fails, there will be an exception.

    So for let () = something, you have a pattern that binds no variables and can never fail (since an expression of type unit can never produce a value other than ()). So this is indeed functionally equivalent let _:unit = ..., just a bit more compact.