(* Exceptions and Options *)
exception Empty
fun max1 xs =
case xs of
[] => raise Empty
| x::xs' => let val m = max1 xs' in
if x > m then x else m end
fun max2 xs =
let fun maxt (m, xs) =
case xs of
[] => m
| x::xs' => maxt (if x>m then x else m, xs')
in
case xs of
[] => raise Empty
| x::xs' => maxt (x, xs')
end
(* Options *)
(* build-in:
datatype 'a option = NONE | SOME of 'a *)
fun max3 xs =
case xs of
[] => NONE
| x::xs' => case (max3 xs') of
NONE => SOME x
| SOME y => SOME (if x > y then x else y)
fun max4 xs =
let fun maxt (m, xs) =
case (m, xs) of
(_, []) => m
| (NONE, x::xs') => maxt (SOME x, xs')
| (SOME y, x::xs') => if x > y
then SOME x
else m
in maxt (NONE, xs) end
(* Look up a value for the key k in the association list xs.
Return NONE if not found or SOME v if k->v found.
*)
val sample_assoc_list = [(1,"hi"), (3,"bye"), (9,"CS"), (251, "251")]
(* : (''a * (''a * 'b) list) -> 'b option *)
fun assoc (k, xs) =
case xs of
[] => NONE
| x::xs' => let val (key,value) = x in
if key=k then SOME value else assoc (k, xs') end
fun assoc2 (k, xs) =
case xs of
[] => NONE
| (key,value)::xs' => if key=k then SOME value else assoc (k, xs')