Get multiple vals from a map

2,193 views
Skip to first unread message

vitalyper

unread,
Dec 1, 2011, 3:23:34 PM12/1/11
to Clojure
Is there something build in for getting multiple vals out of the map?
{:keys [...]} woks in destructuring forms. It is quite easy to build
something with filter and map but I suspect these is a common problem
somebody solved already.
Desired
(get-vals [:a :b] {:a 1 :b 2 :c 3})
(1 2)

Ulises

unread,
Dec 1, 2011, 3:26:31 PM12/1/11
to clo...@googlegroups.com
How about using juxt:

sandbox> ((juxt :foo :bar) {:foo 1 :bar 2 :baz 0})
[1 2]
sandbox>

This only works, however, if you use keywords for keys (as they are
functions themselves).

U

joegallo

unread,
Dec 1, 2011, 3:27:28 PM12/1/11
to clo...@googlegroups.com
((juxt :foo :bar) {:foo 1 :bar 2 :baz 3})

juxt to the rescue

vitalyper

unread,
Dec 1, 2011, 3:33:05 PM12/1/11
to Clojure
Thanks, works in my case.

Alan Malloy

unread,
Dec 1, 2011, 5:02:15 PM12/1/11
to Clojure
I usually use juxt, but a more correct/robust solution is to use map,
with the lookup-map as the function:

(map {:foo 1 :bar 2 :baz 0} [:foo :bar])

vitalyper

unread,
Dec 7, 2011, 12:39:05 PM12/7/11
to Clojure
Thanks, Alan. It is more general solution which also works for keys
that are not keywords
user=> (map {"a" 1 "b" 2 "c" 3} [ "a" "b"])
(1 2)
Reply all
Reply to author
Forward
0 new messages