Search code examples
dictionaryclojurehashmap

map indices with letters in clojure


I am trying to map indices of letters in a string txt in a hashmap, to do so I tried

(let[
indices (map #(hash-map (keyword %1) %2) txt (range (count txt)))]

but what I get is something like

({nil \V} {nil \a} {nil \d} {nil \e} {nil \r} {nil \space} {nil \s} {nil \a} {nil \i} {nil \d} {nil \:} {nil \space} {nil \N} {nil \o} {nil \,} {nil \space} {nil \I} {nil \space} {nil \a} {nil \m} {nil \space} {nil \y} {nil \o} {nil \u} {nil \r} {nil \space} {nil \f} {nil \a} {nil \t} {nil \h} {nil \e} {nil \r} {nil \!})

while what I want is

({:0 \V} {:1 \a} ....

Solution

  • keyword returns nil for numeric arguments so you need to convert the indices into strings first:

    (map #(hash-map (keyword (str %1)) %2)
      (range (count txt))
      txt)
    

    or you can use map-indexed:

    (map-indexed (fn [idx e] {(keyword (str idx)) e}) txt)