Barry SCHWARTZ (Barijo ŜVARC) (chemoelectric) wrote,

Mutability and type signatures

An example of why I prefer immutable values. Compare
type immutable_record = {
  a : int;
  b : int;

let set_a record new_a = { record with a = new_a }

with the mutable version
type mutable_record = {
  mutable a : int;
  mutable b : int;

let set_a' record new_a = record.a <- new_a

The type signature of function set_a is immutable_record -> (int -> immutable_record) (which is just the usual way to write a function taking two arguments, in Caml, though technically it is a function taking one argument that produces another function taking one argument). OTOH the type signature for set_a' is mutable_record -> (int -> unit) where "unit" means there is no meaningful return value. The type signature of the function is opaque as to what is going on within the function. You still can’t break type safety, but more thought is required to keep track of goings-on.

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded