Friday, 1 July 2011

Lambdas in Clojure

The form (fn [...] (....)) is the equivalent of (lambda (...) (....)).  It puts the parameters in a vector [...] rather than a list (...).  This comes in handy later because it clarifies the definitions especially when you use the option to use multiple argument lists.

There is also an alternative economical form for anonymous functions - for example a lambda to add 5 to a number is just #(+ % 5): to compare a number to 5 would be #(> % 5) and so on.  These are just the right size to pop into map and filter functions.  The symbol % stands for the argument to the function.

So for example the question to find the penultimate element of a list, by reversing it and then getting the second element:

(#(second (reverse %)) '(1 2 3 4)) => 3

or using function composition this could be:-

(#((comp second reverse) %) '(1 2 3 4)) => 3

which in this instance is no simpler.

When I came to the example of returning the nth element of a sequence I caught myself starting to write a loop.  Hello?  In low-level languages we write jumps: in middle-level languages we write loops: but in high-level languages we operate on compound data structures as a whole.  The first element is given by the function first.  To get later ones we drop so many from the front of the sequence and then get the first of what's left - so to get the nth element of sq we want (first (drop n sq)).

Yes there is a function nth that does this anyway but the point is to see how that works.

No comments:

Post a Comment