8 Jan 2011 rkrishnan   » (Journeyer)

Clojure's function composition goodness

Sean Devlin, in the Episode 16 of the Full Disclojure posted some really awesome ways to play with tables. One of the nice things he did is worth writing. Due credits go to Sean for posting the code.

Suppose you have a map of people with their name and ages:

(def from-xml [{:name "Sean" :age 27} {:name "Ross" :age 27} {:name "Brian" :age 22}])

Now, you want to have the name and age of people in this list of those with the age 27. Clojure’s comp function comes to the rescue. comp takes some functions and applies them to the data from right to left. i.e., It takes the right most function, applies it to the input parameters, the result of which goes as input to the next right most function and so on. Let us take one single map and pass it to the comp:

user> ((comp #{33} :age) {:name "Ram" :age 33}) 33

What this does is, it takes the input map, applies the :age function on the map (Clojure’s hashmap keys are functions themselves). The result of this is used to see if it falls in the given set (which just has 33).  Now, sets are functions of their members. Here is an example:

user> (#{33 34} 34) 34 user> (#{33 34} 33) 33 user> (#{33 34} 32) nil user> (#{33} 33) 33

We use this composition as a predicate to the filter function which results in the elegant solution that Sean posted.

user> (filter (comp #{27} :age) from-xml) ({:name "Sean", :age 27} {:name "Ross", :age 27})

Note that we get back maps in the same format, which is really nice in certain situations. Sean’s Episode 16 also has quite a lot of other goodness as well.

Syndicated 2010-04-14 07:00:00 from Ramakrishnan Muthukrishnan

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!