OCaml reference types.


(* 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;;

(* references cells can reference polymorphic types *)
type poly = {mutable f : 'a. 'a -> 'a * int};;

let pair = {f = function x -> (x, 3)};;

pair.f 5;;

pair.f true;;

pair.f <- function x -> (x, 6);;

pair.f 5;;

pair.f true;;

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.