简体   繁体   中英

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} ....

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM