Saturday, December 15, 2012

Manipulating vector of maps - Clojure.

So here is a vector of maps.
Map contains name, age and school as keys. Note that school is an optional key.

> (def student-grades
[{:age 21, :name "Mayank", :school "MSB"}
{:age 23, :name "Alex"}
{:age 11, :name "Amit", :school "Ajmer"}])

Now I would like to take that vector of maps and return the same name, increment the age and if school key is missing return "-" as its value else return the school itself.

So I write a function which take one map like that. and de-structure its keys.

> (defn get-grades
  "This will take a map of name age school as keys and return a map of name, incremented age and if school is not given then - else the name of the school itself."
  [{:keys [name age school]}]
  {:name name
   :age (inc age)
   :school (or school "-")})


And now All I have to do is map that function onto that whole vector of maps and we get :

> (map get-grades student-grades)
({:name "Mayank", :age 22, :school "MSB"}
 {:name "Alex", :age 24, :school "-"}
 {:name "Amit", :age 12, :school "Ajmer"})



Notice age has been incremented, and if school is empty it is returning a "-" :)


This took me sometime to grasp but somehow I just got it. So thought i'll share it down.

Reference :  http://blog.jayfields.com/2010/07/clojure-destructuring.html

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.