cpt*_*lly 2 clojure hashmap zipmap
首先,我是The Iron Yard 12周5中的学生,学习Java后端工程.该课程由大约60%的Java,25%的JavaScript和15%的Clojure组成.
我收到了以下问题(在评论中概述):
;; Given an ArrayList of words, return a HashMap> containing a keys for every
;; word's first letter. The value for the key will be an ArrayList of all
;; words in the list that start with that letter. An empty string has no first
;; letter so don't add a key for it.
(defn index-words [word-list]
(loop [word (first word-list)
index {}]
(if (contains? index (subs word 0 1))
(assoc index (subs word 0 1) (let [words (index (subs word 0 1))
word word]
(conj words word)))
(assoc index (subs word 0 1) (conj nil word)))
(if (empty? word-list)
index
(recur (rest word-list) index))))
Run Code Online (Sandbox Code Playgroud)
我能够使用类似的问题,zipmap但我很肯定我错过了这个问题.代码编译但无法运行.
具体来说,我无法在'if'的false子句中更新我的hashmap索引.
我在REPL中测试了这个函数的所有组件,它们是孤立的.但我正在努力把它们放在一起.
供您参考,这是调用word-list的代码.
(let [word-list ["aardvark" "apple" "zamboni" "phone"]]
(printf "index-words(%s) -> %s\n" word-list (index-words word-list)))
Run Code Online (Sandbox Code Playgroud)
我希望不是从社区中获得有效的解决方案,而是希望能够让我的大脑朝着正确的方向前进.
该功能assoc不会修改index.您需要使用assoc返回的新值.同样如此conj:它不会修改您传递它的地图.
我希望,这个答案具有你期望得到的性质:只是你问题所在的指针.
顺便说一句:如果你可以做到PersistentList这一点,那么当使用reduce而不是loop和时,它会成为一个单行recur.一个有趣的功能可能是你update-in.
享受Clojure的乐趣.
| 归档时间: |
|
| 查看次数: |
319 次 |
| 最近记录: |