Functional Functions

Jared Parsons wrote a post very similar to one that I have been wanting to do for a while. Check it out: http://blogs.msdn.com/jaredpar/archive/2008/12/02/mapping-linq-to-f.aspx

His post maps the common C#/VB.NET LINQ methods to F# function names.

I like to think about this a little differently. There are a bunch of well known functions in programming which tend to get used a bit more in functional programming. C#/VB.NET and the BCL names things rather unintuitive if you are accustomed to the functional names for these functions.

The basics:

map Select
reduce Aggregate
filter Where

To throw a little more confusion in the mix, there are aliases and special cases for reduce.

Fold is an implementation of reduce which implies some order to how the reduction is performed. Usually fold is an alias for fold right, which means go from left to right. The other is fold_right which does the same thing but goes from right to left.

Sum, Max, Min and Average are all special cases of Aggregate or reduce.

If you are new to functional programming it will help to remember all of this. Read the wikipedia page for map: http://en.wikipedia.org/wiki/Map_(higher-order_function) and be sure to look in the See also section for the reduce page and the external links for this link: http://www.cse.unsw.edu.au/~en1000/haskell/hof.html

— begin joke here —

F# does an interesting thing and names its generic generator function “unfold” since it is the opposite of fold. This means it is the opposite of reduce. Since any specific functions implemented with fold can be considered a reduction function, and in chemistry reduction has an opposite, I like to call the concept of unfold by the name “oxidate” or “oxidize”. e.g. here is an oxidation function for Fibinacci sequence until the value is one million. It is lifted from Chris Smith’s blog:

let fibs =

        (1,1) |> Seq.unfold

            (fun (n0,n1) ->

                if n0 <= 1000000 then

                    Some (n0, (n1, n0 + n1))

                else

                    None)

Finally, there is one more similar terminology: generators.

Python calls methods like this “generators” although the docs in PEP 255 also calls them “producer functions”. PEP 289 defines a short hand expression for these things which is very similar to F# sequence expressions.

Now that IronPython is 2.0 final and we know F# will be shipped with Visual Studio 2010, please remember that sequence expressions in F# and generator expressions in python are just two forms of oxidation.