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}])
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
: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})
Syndicated 2010-04-14 07:00:00 from Ramakrishnan Muthukrishnan
