These expressions are equivalent in any context. But in ‘not-Ocaml’:
Assignments can eliminate referential transparency
OCaml supports typed references, which refer to memory cells on the heap. The type rules for references are:
Notice that with references, order of evaluation is important
We can force OCaml to evaluate a sequence of expressions in order using nested lets:
Note 1: ;
is a separator, not a terminator.
Note 2: you’ll get a compiler warning if any of e1
, e2
, …, en
does not have type unit
.
What about operators and function calls?
In OCaml, this is specified but the programmer must know; the behavior of f(++x,x++);
is “implementation specific” in C!
Despite these drawbacks, some things are easiest to compute with assignment.
lazy
Example: “under the hood” of the Lazy
module:
References are a common source of “monomorphic type variables:”
# let r = ref [] ;;
val r : '_weak1 list ref = ...
# r := [1] ;;
- : unit = ()
# r ;;
val r : int list ref = ...
Only immutable values can have polymorphic type in OCaml…
cs2041.org