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/.
Creating XElements
Nothing amazing, but I keep getting caught out by the implicit conversion of XNames:
Multi-Line Strings
This is pretty trivial, but it seems to be a feature of F# strings that is not widely known.
This produces:
When the F# compiler sees a back-slash followed by a carriage return inside a string literal, it will remove everything from the back-slash to the first non-space character on the next line. This allows you to have multi-line string literals that line up, without using a bunch of string concatenation.
Scale/Ratio function builder
Again, trivial, but handy.
Example:
Transposing a list (seen on Jomo Fisher's blog)
And here is a tail-recursive version which (from my sketchy profiling) is mildly slower, but has the advantage of not throwing a stack overflow when the inner lists are longer than 10000 elements (on my machine):
If I was clever, I'd try and parallelise it with async...
DataSetExtensions for F#, DataReaders
System.Data.DataSetExtensions.dll adds the ability to treat a
DataTable
as anIEnumerable<DataRow>
as well as unboxing the values of individual cells in a way that gracefully handlesDBNull
by supporting System.Nullable. For example, in C# we can get the value of an integer column that contains nulls, and specify thatDBNull
should default to zero with a very concise syntax:There are two areas where DataSetExtensions are lacking, however. First, it doesn't support
IDataReader
and second, it doesn't support the F#option
type. The following code does both - it allows anIDataReader
to be treated as aseq<IDataRecord>
, and it can unbox values from either a reader or a dataset, with support for F# options or System.Nullable. Combined with the option-coalescing operator in another answer, this allows for code such as the following when working with a DataReader:Perhaps a more idiomatic F# way of ignoring database nulls would be...
Further, the extension methods defined below are usable from both F# and from C#/VB.
Parallel map