This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* 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 | |
*) | |
No comments:
Post a Comment