(* CSE 341 Lecture 9 - Code examples *)
(* 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 *)
fun empty_set () =
let fun exists lst =
fn j =>
let fun iter rest =
case rest of
[] => false
| hd::tl => j=hd orelse iter tl
in iter lst end
fun make_set lst =(*lst a "private field"*)
S{ add = fn i => make_set (i::lst),
member = exists 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
(* simple example of currying *)
fun add x y = x+y;
val addone = add 1;
(* we could have written add without using 'fun', as follows: *)
val otheradd = (fn x => (fn y => x+y))
(* the built-in versions of map, foldl, and foldr in the Standard ML Basis
Library are curried *)
val addone_list = map addone;
val sum = foldr (op +) 0;
(* we could define map etc ourselves as well, of course *)
fun mymap f [] = []
| mymap f (x::xs) = f x :: mymap f xs
(* curried version of filter *)
fun myfilter f [] = []
| myfilter f (x::xs) = if f x
then x :: myfilter f xs
else myfilter f xs
fun iseven j = j mod 2 = 0;
val evens = myfilter iseven;
(* curried version of member - test whether something is a member of a list *)
fun member x [] = false
| member x (y::ys) = if x=y then true else member x ys
(* sort of silly function to test whether a list contains 13 *)
val unlucky = member 13;