References in ML: -- An ML reference is a value which is the address of a location in the memory. -- The value in the location is the content. -- The content can be read through the dereferenceing operation and changed through an assignment operation. [1] Creating a reference Using the constructor: ref -- Ref is an ML function. -- It expects an argument, the initial content of the reference. -- It returns a new address every time it is called. - val x = ref 2; val x = ref 2 : int ref - val y = ref 5; val y = ref 5 : int ref [2] Dereferencing Using the function: ! -- When ! is applied to a reference, it returns its contents. - !x; val it = 2 : int - !y; val it = 5 : int [3] Updating Using the assignment operator: := -- := operation updates the value of a reference. -- The type of := is unit. - x := !x + 2; val it = () : unit - x; val it = ref 4 : int ref - !x; val it = 4 : int - y := !x + 5; val it = () : unit - y; val it = ref 9 : int ref - !y; val it = 9 : int [4] Sequencing Syntax: (E1; E2; ... ; En) -- The expressions are evaluated from left to right. -- The result is the value of En. -- The value of E1 to En-1 will be discarded. They are used for side effects. - (x := !x + 3; y := !x + 4); val it = () : unit - x; val it = ref 7 : int ref - y; val it = ref 11 : int ref [5] More examples Tuples: - val a = ref 2; val a = ref 2 : int ref - val b= ref 3; val b = ref 3 : int ref - (a, b); val it = (ref 2,ref 3) : int ref * int ref Lists: - val c = ref 4; val c = ref 4 : int ref - val s = [a, b, c]; val s = [ref 2,ref 3,ref 4] : int ref list - hd s; val it = ref 2 : int ref - tl s; val it = [ref 3,ref 4] : int ref list