Options

Posted by Beetle B. on Tue 02 August 2016

Consider this motivating example: I want to write a function that takes a list of integers, and returns its sum.

What should it return if the list is empty? 0 is a bad answer. Raising an exception may be OK, but in some cases we write our functions recursively to allow for an empty list.

In Standard ML, we can return NONE or SOME e. If a function returns NONE, it means there is no value. If it returns SOME e, then there is. It evaluates e and carries the value of it.

The type of NONE is 'a option. The type of SOME e is t option where t is the type of e.

Given such a value, how do we use it? isSome evaluates to false if the value is NONE. valOf returns the value if there is one.

Example taken straight from Dan Grossman’s Coursera course.

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

In reality, it is better to use case than isSome and valOf.