Destructuring let and :syms and :strs?

551 views
Skip to first unread message

Rhialto

unread,
Aug 3, 2008, 4:56:40 PM8/3/08
to Clojure
Hi,

I am reading the clojure documentation and I have no ideas of the
meaning that sentence in the
let documentation.

...
It is often the case that you will want to bind same-named symbols to
the map keys. The :keys directive allows you to avoid the redundancy:

(let [{fred :fred ethel :ethel lucy :lucy} m] ...

can be written:

(let [{:keys [fred ethel lucy]} m] ...

There are similar :strs and :syms directives for matching string and
symbol keys.

Any examples? For the use of these directives ":strs, :syms".

Paul Drummond

unread,
Aug 4, 2008, 5:33:26 AM8/4/08
to Clojure
Hi Rhialto,

Keys in Clojure don't have to be keywords - a map can contain strings
and symbols as keys so the first shorthand {:keys [fred ethel lucy]}
works when the keys in your map are keywords (which is the default
because keys are usually keywords in Clojure). But if your map
happens to use strings or symbols for the keys that's when the other
directives would be used (:strs, :syms).

Examples:

user=> ;;EXAMPLE 1 - map contains keyword as key
(let [ {:keys [fred ethel lucy]} {:fred "value of fred key"}] (print
fred))
value of fred keynil

user=> ;;EXAMPLE 2 - map contains string as keyword so :strs directive
is used
(let [ {:strs [fred ethel lucy]} {"fred" "FRED"}] (print fred))
FREDnil

user=> ;;EXAMPLE 3 - map contains string as keyword but :keys
directive is used so it doesn't work as expected
(let [ {:keys [fred ethel lucy]} {"fred" "FRED"}] (print fred))
nilnil

Hope that helps,
Paul
Reply all
Reply to author
Forward
0 new messages