Reputation: 748
In my previous question yesterday Getting max value from a list in SML, I figured out with the help of Andreas Rossberg how to evaluate a function that gets the Max of a list of integers using SML.
Continuing on to my study. The same code was revised to use Options. Here is the code
fun max1 (xs : int list) =
if null xs
then NONE
else
let val tl_ans = max1(tl xs)
in
if isSome tl_ans andalso valOf tl_ans > hd xs
then tl_ans
else SOME (hd xs)
end
I have the following questions:
option
?option
s?Upvotes: 2
Views: 136
Reputation: 5038
A comment on your first question: not only the else-branch results in a value of type option
, this is also true for the if-branch (i.e., NONE
). In general both branches of an if-construct have to have the same type.
As for your second question. The option
type is often used to explicitly encode partiality of a function (i.e., if there is no proper result for input). In the case of getting the maximum value contained in a list this happens when the input is the empty list. With the function from you previous post we get
max [] = 0
(in words: the maximum value contained in the empty list is 0), which is somehow wrong since we would for example also get
max [0] = 0
To distinguish these two cases we can use the option
type, resulting in
max1 [] = NONE
max1 [0] = SOME 0
The reason for returning an option type, in this case an 'int option
, is that we get more fine-grained information: firstly, already the type of max1
, i.e., int list => int option
, tells us that the function is partial (we might either get SOME
result or NONE
); secondly, whenever we get NONE
we know that the input was the empty list.
Upvotes: 7