If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Saturday, October 12, 2013

Using pattern matching instead of using head or tail

(* in a previous post we saw how we could define a max function by testing
- if a list is empty with null
- extracting a value from an option with valOf
BUT that is considered bad practise so instead we will switch to using pattern matching
Because both list AND option are defined as algebraic datatypes
fun max(numbers: int list) =
if null numbers
then NONE
else
let val max_tail = max(tl numbers)
in
if max_tail = NONE orelse hd numbers >= valOf max_tail
then SOME (hd numbers)
else max_tail
end;
can be rewritten to
*)
fun max(numbers: int list): int option =
case numbers of
[] => NONE
| x::xs =>
case max xs of
NONE => SOME x
|SOME y => SOME (Int.max(x, y))
val test1 = max([3,6,4,2])
val test2 = max([])
(* output of program
[opening patternmatching.sml]
val max = fn : int list -> int option
val test1 = SOME 6 : int option
val test2 = NONE : int option
val it = () : unit
*)
view raw gistfile1.sml hosted with ❤ by GitHub

No comments:

Post a Comment