The big brains in FP have for a long time shared Functional Pearls: > elegant, instructive examples of functional programming. They are supposed to be fun, and they teach important programming techniques and fundamental design principles
A Cookie is a (sometimes) elegant use of the particularly flexible and concise syntax of the language to create a “mouthful” of programming goodness. In other words we take syntactic sugar and make something delicious. As with most kinds of cookies, I make no claim that any of these are good for you, but I hope you’ll enjoy them nonetheless.
Let’s get started with removing some boilerplate when parsing numeric values out of a string.
This code allows us to use the
TryParse static method that is common to most of the BCL numeric types, e.g. Byte, Int32, etc. implicitly.
It does this through the use of statically-resolved type parameters. This is an extremely powerful feature that enables all kinds of
wonderment, though it can be difficult to get the syntax right at first.
Speaking of statically resolved types, Mauricio and Lev are the great chefs behind this next cookie.
With a little bit of hacking with Fleece (see also)
I was able to obtain this result:
The cool thing here is the use of the
(?) operator to change
jget json "someKey" to
json?someKey. The use of a question mark also points at the “maybe” semantics; very tasty!
You should definitely read this year’s advent article from Rachel to learn more about this kind of thing.
Finally, I’ll leave you with a really unhealthy batch.
Besides being a silly way to send holiday greetings, the
(|Twelvetide|) pattern show that F# allows an active pattern match in a parameter. Parameters are patterns;
most of the time they are of the form
(arg : T), but just as you can write
let (Some f') = f you can write
let f (Some s') = s. Really, you should avoid doing this and pay
attention to the compiler warnings to avoid runtime exceptions, but it does highlight how central pattern matching is to F#.