(* Dan Grossman, CSE341 Winter 2008, Lecture 9 *)
(* An ADT using higher-order functions *)
(* a set with two operations ("methods") *)
datatype set = S of { add : int -> set, member : int -> bool }
(* a set constructor *)
val empty_set =
let fun exists(j,lst) = (* could use currying and/or fold to be fancier *)
case lst of
[] => false
| hd::tl => j=hd orelse exists(j,tl)
fun make_set lst = (* lst is a "private field" *)
S { add = fn i => make_set (i::lst),
member = fn i => exists (i,lst) }
in
make_set []
end
(* example client *)
fun use_a_set () =
let val S s1 = empty_set
val S s2 = (#add s1) 34
val S s3 = (#add s2) 19
in
if (#member s3) 42
then 99
else if (#member s3) 19
then 17
else 0
end