2

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?

Community
  • 1
  • 1
Mars
  • 8,689
  • 2
  • 42
  • 70
  • what does "simpler" mean for you? and why do you want more simpler solution? `apply concat` seems very simple solution at least for me. – ymonad May 01 '14 at 05:44
  • `apply concat` is fine, @ymonad. I don't need a simpler solution. It's common to discover that there's a single Clojure function that does something simple and obvious (converting a map to a sequence, in this case) that one didn't realize would have that effect. It's helpful to know those options. (I suppose, also, that in general I feel that using `apply` except when you have a collection argument that would normally be the `rest` of a list with a function in its `first`, is, I don't know ..., aesthetically unpleasant.) – Mars May 01 '14 at 15:06
  • 2
    For eager conversion to a vector of alternating keys and values: `(reduce into {:a 1 :b 2})`. – A. Webb May 01 '14 at 15:18

2 Answers2

3

You can also do

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

or

(mapcat seq {:a 1 :b 2})
KobbyPemson
  • 2,519
  • 1
  • 18
  • 33
1

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.

Thumbnail
  • 13,293
  • 2
  • 29
  • 37
  • 5
    `flatten` is almost always the wrong thing to use, it destroys the structure of your keys and values (if they have any) – noisesmith May 01 '14 at 14:32
  • 2
    @noisesmith I agree. OP's solution - essentially `(partial apply concat)` - is accurate and credible. – Thumbnail May 01 '14 at 14:56