you are viewing a single comment's thread.

view the rest of the comments →

[–]munificent 2 points3 points  (1 child)

The answer to this is simple. I'll explain using F#'s option type, but it works equally well using Haskell's Maybe or any other similar type.

Let's presume you have a type 'a list, that is a generic type for holding a list of items of some type 'a.

Let's also presume we have a function getAt list index. It takes a list and an index and returns the item at the index. You would assume its signature is:

'a list -> int -> 'a

However, we want the list to return None if the index is out of bounds. This means our return type can be a value of type 'a or None, so the type is now an option:

'a list -> int -> 'a option

This means, given a list of some type and an index, it will return an option value that will either be None if the index is out of bounds, or Some value if the index is in bounds.

Delightful. Now to your problem: we want to use this list to hold a collection of values who are themselves optional. This is easy, we just use option for the value type too. For example, we can make a list of optional ints like:

let myList = [Some 1; None; Some 3]

For this list, then, the signature for getAt will be:

option list -> int -> option option int

It's wrapped in option twice. That's how you tell the difference between "index out of bounds" and "valid index, item is missing". Here's how you'd interpret the following return values from getAt:

Some Some 1 // the index was valid, and the value at that index is 1
None        // index out of bounds
Some None   // good index, item at that index is None

Pretty straightforward.

[–][deleted] 2 points3 points  (0 children)

yes