murtaza52
murtaza52

Reputation: 47441

destructuring in clojure - embedded maps

I encountered the below destructuring in a ring handler function -

[{{:keys [params remote]} :params :as request}]

Its strange as this is the first time I have seen two levels of braces. Does clojure support n levels in destructuring ? I am assuming in the above the :params map is being destructured into [params remote] ?

Upvotes: 2

Views: 1055

Answers (1)

okonomichiyaki
okonomichiyaki

Reputation: 8485

Yes, Clojure supports destructuring nested data structures, although I don't know if it supports arbitrarily deep nesting. Here's a simple example of destructuring a map, where one of the two keys has a vector for its corresponding value:

(let [{[x y] :pos c :color}
      {:color "blue" :pos [1 2]}]
  [x y c])

Your example is more than that though, since it also uses the :keys directive, which binds a local variable with the same name as a map's keys. The following are equivalent:

(let [{{:keys [params remotes]} :params}
      {:params {:params "PARAMS" :remotes "REMOTES"}}]
  [remotes params])

(let [{{params :params remotes :remotes} :params}
      {:params {:params "PARAMS" :remotes "REMOTES"}}]
  [remotes params])

Both evaluate to ["REMOTES" "PARAMS"].

Upvotes: 5

Related Questions