【问题标题】:Clojure: Implementing the assoc-in functionClojure:实现关联函数
【发布时间】:2016-12-11 07:29:34
【问题描述】:

Clojure 中的Chapter 5, Exercise 3 要求:

实现关联函数。提示:使用assoc函数并将其参数定义为[m [k & ks] v]

虽然我找到了solution(参见第 39-54 行),但我想知道是否有不同的方法。在进行上一个练习时,我发现 jbm 在implementing the comp function 上的这个非常明确的答案非常有帮助。

我一直在尝试减少键的联合列表上的部分关联,并将返回的函数应用于最终值:

(defn my-part-assoc [m k]
  (partial assoc m k))

((reduce my-part-assoc {} [:one :two :three]) "val")

不用说,这是行不通的。我是 Clojure 和函数式编程的新手,我担心我对 reduce 的基本理解会导致我走错路。请问有人可以提供更简洁的答案吗?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    发布后不久,我找到了this,它从Clojure GitHub repo得到以下定义:

    (defn assoc-in
      ;; metadata elided
      [m [k & ks] v]
      (if ks
        (assoc m k (assoc-in (get m k) ks v))
        (assoc m k v)))
    

    【讨论】:

    • 我不确定这是否构成重复。虽然我在 Stack Overflow 上找到了我的答案,但我仍然保留我的问题,因为它非常具体,可能会帮助处于相同位置的其他人。
    • 请注意,与核心版本不同,您的版本会失败:(assoc-in {} [:a :b :c] 1)...
    【解决方案2】:

    这是一个不使用“assoc-in”的解决方案,这似乎是一个要求:

    (defn my-assoc-in
      [m [k & ks] v]
      (if (= (count ks) 0)
        (assoc m k v)
        (let [ordered-ks (reverse ks)
              first-m (get-in m (butlast (cons k ks)))]
          (assoc m k (reduce
                      (fn [curr-m next-k] (assoc {} next-k curr-m))
                      (assoc first-m (first ordered-ks) v)
                      (rest ordered-ks))))))```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多