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?
The option type in F# is used when an actual value might not exist for a named value or variable. An option has an underlying type and can hold a value of that type, or it might not have a value.
What is it? An Option type for C#. Options are a well studied Functional paradigm that allows for the representation of not having a value (None) as well as having a value (Some). This allows for a clear differentiation without the need for null values.
The null keyword is a valid keyword in F#, and you have to use it when you are working with . NET Framework APIs or other APIs that are written in another . NET language.
To add to the other answers, the Option type is nothing special -- it's just another discriminated union. You could define it yourself in one line:
type 'a Option = None | Some of 'a
The utility, as others have pointed out, is that pattern matching will let you safely deconstruct this, instead of checking for null or using some hack-workaround to indicate if a value isn't really a value.
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.
It's used when a function or method should "maybe" or "optionally" return a value. In C# you'd probably return null, or return a Null Object or possibly a Nullable for value types.
The downside of returning null (the most common case) is that it's not type safe: null is an instance of all types, so you get into all kinds of hairy null reference situations later on.
The Option type is a so called disciminated union type with two constructors: None and Some a. None explicitly indicates that you don't have a value. Basically it's the Null Object pattern generalized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With