There are already two questions about F#/functional snippets.
However what I'm looking for here are useful snippets, little 'helper' functions that are reusable. Or obscure but nifty patterns that you can never quite remember.
Something like:
open System.IO
let rec visitor dir filter=
seq { yield! Directory.GetFiles(dir, filter)
for subdir in Directory.GetDirectories(dir) do
yield! visitor subdir filter}
I'd like to make this a kind of handy reference page. As such there will be no right answer, but hopefully lots of good ones.
EDIT Tomas Petricek has created a site specifically for F# snippets http://fssnip.net/.
'Unitize' a function which doesn't handle units Using the
FloatWithMeasure
function http://msdn.microsoft.com/en-us/library/ee806527(VS.100).aspx.Example:
OLD version:
Kudos to kvb
Option-coalescing operators
I wanted a version of the
defaultArg
function that had a syntax closer to the C# null-coalescing operator,??
. This lets me get the value from an Option while providing a default value, using a very concise syntax.Performance testing
(Found here and updated for latest release of F#)
LINQ-to-XML helpers
Tree-sort / Flatten a tree into a list
I have the following binary tree:
Which is represented as follows:
A straightforward method to flatten the tree is:
This isn't tail-recursive, and I believe the
@
operator causes it to be O(n log n) or O(n^2) with unbalanced binary trees. With a little tweaking, I came up with this tail-recursive O(n) version:Here's the output in fsi:
Maybe monad
Here's a brief intro to monads for the uninitiated.