ML reference type and mutable data

These examples demonstrate mutable types in ML, i.e. types where data can be changed.


(* C:\Documents and Settings\Default\Desktop\4651\examples\references.ml *)

let x = ref 5;;

x := !x + 1;;

x;;

(* a record with two mutable fields *)
type changeme = {mutable n: int; mutable s: string};;

let y = {n = 3; s = "apple"};;

y.s <- "banana";;

y;;

let sum = ref 0;;

(* find_sum modifies a global mutable variable sum *)
(* () is the unit element, represents "do nothing" *) 

let rec find_sum = function 
[] -> ()         
| x :: xs -> sum := !sum + x; find_sum xs;;

let l = [2; 7; 9];;

find_sum l;;

sum;;

sum := 0;;

find_sum [];;

sum;;

sum := 0;;

find_sum [1; 2 ; 4; 8; -7];;

sum;;

(* using a local variable in a function *)
let f x = 
  let r = ref 0 in
  if (x < 5) then (r := 6; !r)
  else (r := 8; !r);;

(* a random number generator*)
let current_rand = ref 0;;

let random () =
   current_rand := !current_rand * 25713 + 1345; 
   !current_rand;;

random();;

!current_rand;;

random();;

!current_rand;;

(* mutable types *)
(* I could make x mutable and y immutable *)
type mutable_pair = {mutable x: int; mutable y: int};;

let my_pair = {x = 5; y = 6};;

my_pair.x <- 99;;

my_pair.x;;


This is an example from CSci 4651 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.