What are the advantages of using Options for getting the Max of a list of integers in SML

StackOverflow https://stackoverflow.com/questions/20832413

  •  22-09-2022
  •  | 
  •  

Question

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:

  1. Why does the code inside the else statement output a value of type option?
  2. What are the advantages of using options?
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top