Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting key-values into map conditionally, what are the concise ways?

Tags:

clojure

What are the concise/ elegant ways to put into a map key-value pairs for which the corresponding conditions are true?

That is to translate

[condition1 condition2 ...] [key1 val1 key2 val2 ...]

or

[condition1 condition2 ...] [key1 key2 ...] [val1 val2 ...]

or

[condition1 key1 val1 condition2 key2 val2...]

into

{key-for-true-condition1 val-for-true-condition1, key-for-true-condition2 val-for-true-condition2...}

I think to use "reduce" with "if" in its lambda but interested in more concise/ beautiful/ elegant/ idiomatic ways.

like image 815
Sergey Avatar asked Feb 02 '23 20:02

Sergey


1 Answers

(into {} (for [[c k v] (partition 3 coll) :when c] 
    [k v])) 

Based on the 'for'-Version from Kintaro but a little shorter.

like image 188
nickik Avatar answered Jun 09 '23 11:06

nickik