If you're just joining us, below is the path that has brought us to this point.
Today, we're taking a high-level look at F# option types. Option types are a simple example of a discriminated (or tagged) union1, although understanding that isn't necessary in order to use them. Simply put, an option type wraps a value with information indicating whether or not the value exists. For C# or VB programmers, it may be convenient to think of option types as a mutant cross between .NET 2.0 nullable types and the null object design pattern.
There are two constructors that instantiate option types. First, there's the Some constructor, which takes a value to be wrapped.
And then, there's the None constructor, which doesn't take anything.
One of the properties of option types that makes them so compelling is the ability to pattern match over them.
Now, we can call our isFortyTwo function to show that the pattern matching works as expected.
This is all well and good, but we need a practical example to sink our teeth into. Let's use the .NET Framework Stream.ReadByte function as a guinea pig. ([ed.] Dustin is not implying that you should sink your teeth into guinea pigs. That's disgusting. Shame on you.)
Stream.ReadByte has a pretty bad code smell. First of all, it returns an int instead of a byte. Initially, that should seem strange since the method specifically states that it's a byte generator. ReadByte returns -1 when the current position is at the end of the stream. Because -1 is not expressible as an unsigned byte, ReadByte returns an int. Of course, that's the second problem: extra non-obvious information is encoded into the result value of this function. However, unless you read the documentation, there's no way of knowing that.
By employing an option type, we can clarify the function and be a bit more honest about its result.
Now, the semantics of the function are better expressed thanks to the option type.
In addition, we can write a function that pattern matches over the result of our readByte function.
And here's the above printStream function in action:
Option types provide an elegant way to attach a bit of extra boolean information to a value. It's important to become comfortable with them as they are used extensively throughout the F# libraries.
Have fun! Next we'll explore... well... I haven't decided yet. If you have any suggestions, feel free to email me at dustin AT diditwith.net.
1We'll explore discriminated unions in a future article.
Page rendered at Saturday, October 11, 2008 1:51:17 AM (Eastern Standard Time, UTC-05:00)