clojure - 从 clojure 中的数组构建 HashMap

标签 clojure hashmap zipmap

首先,我是 The Iron Yard 的 12 周第 5 周的学生,学习 Java 后端工程。该类(class)大约由 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))))

我能够使用 zipmap 解决类似的问题,但我确信我在这个问题上遗漏了一些东西。代码可以编译但无法运行。

具体来说,我无法在“if”的 false 子句中更新我的 HashMap 索引。

我已经在 REPL 中测试了该功能的所有组件,它们是独立工作的。但我正在努力将它们放在一起。

以下是调用单词列表的代码,供您引用。

  (let [word-list ["aardvark" "apple" "zamboni" "phone"]]
    (printf "index-words(%s) -> %s\n" word-list (index-words word-list)))

我希望得到一些指导,让我的大脑朝着正确的方向发展,而不是从社区获得可行的解决方案。

最佳答案

函数assoc不会修改index。您需要使用 assoc 返回的新值。 conj 也是如此:它不会修改您传递给它的 map 。

我希望这个答案符合您期望得到的性质:只是指出您的问题所在。

顺便说一句:如果您可以使用PersistentList,那么当使用reduce而不是looprecur时,这将成为一行update-in 可能是您感兴趣的一个函数。

享受 Clojure 的乐趣。

关于clojure - 从 clojure 中的数组构建 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307670/

相关文章:

clojure - 如何在本地 repl 中查看 Clojure 局部变量?

concurrency - 在 Clojure 中处理同时发生的重复事件

kotlin - 有没有办法让函数在从 map 查找时不返回 null

redis - 为什么 Redis Hash Bucket 省磁盘?

clojure - 带有多值键的 zipmap

clojure - 在 Clojure 的嵌套语法引号中协调自动生成符号

clojure - 为什么 `dir` 不适用于从 "current namespace var"- `*ns*` 获取的当前命名空间

Java ConcurrentHashmap 问题

c++ - C++ 中的 map 与 hash_map