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.