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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The option type is at least similar to
Nullable<T>and reference types in C#. A value of typeOption<T>is eitherNonewhich means there’s no encapsuated value, orSomewith a particular value ofT. This is just like the way aNullable<int>in C# is either the null value, or has an associatedint– and the way aStringvalue 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:
is similar to:
I believe the general idea is that forcing you (well, nearly) to handle the ‘no associated value/object’ case makes your code more robust.