People interested in the advantages for F# might do well to take a look at F# option type. This allows an F# programmer to specify the presents or absence of some data much the same way a C# programmer might use a null reference.
Let us take a quick look at how you might use the option type. It is implemented as a discriminating union so can be investigated with F#’s pattern matching constructs.
let nodeText = match (get_single_node node “/fruit/apples”) with
| None -> “”
| Some node -> get_node_text node
If we imagine get_single_node and get_node_text are functions from a ml style Xml api, we can see that above snippet will get the inner text from a single node at the location “/fruit/apples” and if the node does not exist it will return the empty string.
At first this may look overly verbose if you compare it with a similar C# snippet.
string nodeText = node.SelectSingleNode(“/fruit/apples”).Value
But here the C# programmer has made a mistake which is common amongst the young players. If the node does not exist then this snippet will throw a NullReferenceException, this can be a nightmare to debug if a method contains lots of statements like the above, as it can be difficult to spot which item is returning null.
While there is nothing stop the C# programmer checking the item returned reference to set a default value, or throw a more meaningful exception. In the F# way of doing this the programmer is reminded to do this as the compiler will issue an incomplete pattern matching warning if they forget to set a default value.