3 ms·
What does this even mean? OCaml's variables are immutable. To use mutation, you have to do so explicitly with the `ref` type, e.g.: let box = ref 0 in
by DonaldPShimoda 5y ago
What does this even mean?
OCaml's variables are immutable. To use mutation, you have to do so explicitly with the `ref` type, e.g.:
let box = ref 0 in
print_endline ("box value: " ++ int_of_string !box);
box := !box + 1;
print_endline ("box value: " ++ int_of_string !box)
will print first `0` and then `1`. You cannot put a non-integer into the box because the box has type `int ref`, meaning only values of type `int` can be put into it with the `:=` operator.
- kccqzy 5y agoGP is (rhetorically, I assume) asking about whether or not the action of incrementing the mutable variable is typed, not that the variable itself is typed. For example in normal Haskell the code that uses mutation and code that does not use mutation have different types. A function may have the type f :: Int -> Int but with mutation it can become f :: Int -> ST s Int or f :: Int -> IO Int or f :: Int -> STM Int depending on the circumstances. That's not the case in OCaml. The kind of mutation in OCaml references is the most similar to Haskell's ST monad (not to be confused with State or StateT), but in Haskell the type tells us a mutation is happening inside the function call.
- bitwize 5y agoOne of the things that Haskell and monads bring to the table is typed side effects. Each action in a monadic computation has a type and cannot be freely mixed with other actions of different types. Of course, it's much easier and more convenient to go side-effecting willy nilly, as OCaml and imperative languages let you do, but that creates too many places for bugs to creep in and hide. Monadic programming gives you more control over what side effects are allowed when.