How does the option type work in F#


Question

So I've been reading the Expert F# book by Apress, mostly using it as a reference when building a toy-ish F# library, but there's one thing I've failed to grasp and that's the "Option" type.

How does it work and what is it's real world usage?

1
9
3/8/2009 7:14:30 PM

Accepted Answer

The option type is at least similar to Nullable<T> and reference types in C#. A value of type Option<T> is either None which means there's no encapsuated value, or Some with a particular value of T. This is just like the way a Nullable<int> in C# is either the null value, or has an associated int - and the way a String value in C# is either a null reference, or refers to a String object.

When you use an option value, you generally specify two paths - one for the case where there is an associated value, and one where there isn't. In other words, this code:

let stringLength (str:Option<string>) =
  match str with
  | Some(v) -> v.Length
  | None -> -1

is similar to:

int StringLength(string str)
{
    if (str != null)
    {
        return str.Length;
    }
    else
    {
        return -1;
    }
}

I believe the general idea is that forcing you (well, nearly) to handle the "no associated value/object" case makes your code more robust.

20
3/8/2009 10:20:50 PM

One of the best examples of real-world usage is for the TryParse pattern in .Net. See the first half of

http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!181.entry

for a discussion.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon