> 2) Is there a good way of doing this with nested maps?  An example:
>
> { :user { :first "John" :last "Doe" :dob { :month 12 :day 30 :year 2012
> :garbage "asdf" } } }
>
> I would want to make sure :dob only contains keys :month, :day, :year.

I'd write a simple little helper function to do this, if I were you.
This is what I came up with.


(defn transform-map [model element]
  (cond
   (sequential? model) (if (sequential? element)
                         (map #(transform-map (first model) %) element)
                         nil)
   (associative? model) (into {} (for [[k v] model
                                       :when (contains? element k)
                                       :let [new-value (transform-map
v (get element k))]
                                       :when (not= new-value ::ignore)]
                                   [k new-value]))
   (ifn? model) (model element)
   model element
   :else ::ignore))



This transforms a value with a `model`. The model consists of nested
maps/vectors which specify what you want the final data to look like.
The leaves of the model are either transformation functions (which are
applied to the value at that point), truthy values (in which case the
value is kept) or falsy values (in which case the value is discarded).
Things which aren't specified are also discarded.

For example:
(def model {:user {:first true
                   :last true
                   :dob {:year true
                         :month true
                         :day true}}})

(transform-map model
               {:user {:first "John"
                       :last "Doe"
                       :dob {:month 12
                             :day 30
                             :year 2012
                             :garbage "asdf"}
                       :role :whatever}})
;=> {:user {:last "Doe", :dob {:year 2012, :month 12, :day 30}, :first "John"}}

I hope that helps!

Carlo

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to