Hi,
I find myself repeating a certain pattern from time to time.
I have a map like this:
{:answer_correct_1 2 :answer_correct_3 4 :foo "bar"}
There is a hidden index answer_correct_idx which might range from 1 to x.
So, what I want is to "iterate" over the map and produce a vec of maps
given some other fields like this:
[{:id 123 :answer_correct_1 2} {:id 123 :answer_correct_3 4} ...]
The pattern that I use then is reduce like this:
(reduce
(fn [a b]
(let [id-correct (keyword (str "answer_correct_" b))]
(if (id-correct params)
(conj a {:question_id q-id :user_id user-id :answer_id (id-correct
params)})
a)))
[] (range 1 11))
If have an if condition inside the reduce and then either conj or return
the unchanged vec. This works. But I wondered if there is a higher
abstraction for it and a very nice guy on slack proposed this:
(let [->id (comp keyword (partial str "answer_correct_"))]
(map
(partial hash-map :question_id q-id :user_id user-id :answer_id)
(keep
(partial get params)
(map ->id (range 1 11)))))
It also works, but, regarding readibility I don't think it's easier to get
(this is subjective of course).
Are there other ways to achieve the same? Maybe something a bit more dense?
Thanks,
Sven
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.