triplej
triplej

Reputation: 299

How do I turn a sequence of sequences into a map, where the values are the count of the first item in the sequence?

I have data like (("generic" 7) ("ore" 1) ("generic" 4) ("wood" 6) ("wheat" 3) ("generic" 2) ("generic" 9) ("sheep" 5) ("brick" 8))

and I want to turn it into

 {"brick"   1
  "generic" 4
  "sheep"   1
  "ore"     1
  "wheat"   1
  "wood"    1}

Since "generic" appears 4 times in the data, I want the key to be "generic" and the value to be 4. Since "sheep" appears 1 time in the data, I want the key to be "sheep" and the value to be "1".

Upvotes: 0

Views: 77

Answers (1)

Martin Půda
Martin Půda

Reputation: 7568

Use map, first and frequencies:

(->> '(("generic" 7) ("ore" 1) ("generic" 4) ("wood" 6) ("wheat" 3) ("generic" 2) ("generic" 9) ("sheep" 5) ("brick" 8))
     (map first)
     frequencies)

=> {"generic" 4, "ore" 1, "wood" 1, "wheat" 1, "sheep" 1, "brick" 1}

(->> is "thread-last" macro.)

Upvotes: 3

Related Questions