Вопрос

Answers to this question explain how to convert maps, sequences, etc. to various sequences and collections, but do not say how to convert a map to a sequence of alternating keys and values. Here is one way:

(apply concat {:a 1 :b 2})
=> (:b 2 :a 1)

Some alternatives that one might naively think would produce the same result, don't, including passing the map to vec, vector, seq, sequence, into [], into (), and flatten. (Sometimes it's easier to try it than to think it through.)

Is there anything simpler than apply concat?

Это было полезно?

Решение

You can also do

(mapcat identity {:a 1 :b 2})

or

(mapcat seq {:a 1 :b 2})

Другие советы

As @noisesmith gently hints below, the following answer is seductive but wrong: left as a warning to other unwary souls! Counterexample:

((comp flatten seq) {[1 2] [3 4], 5 [6 7]})
; (1 2 3 4 5 6 7)

(comp flatten seq) does the job:

((comp flatten seq) {1 2, 3 4})
; (1 2 3 4)

But flatten on its own doesn't:

(flatten {1 2, 3 4})
; ()

I'm surprised it doesn't work, and in that case it should return nil, not ().

None of the others you mention: vec, vector ... , does anything to the individual [key value] pairs that the map presents itself as a sequence of.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top