dictionary - Clojure - 沿着路径行走

标签 dictionary data-structures clojure clojurescript

我正在寻找类似于 clojure.walk 中的功能有 inner作为参数的函数:

  • 不是键和值,就像 clojure.walk/walk 函数
  • 但是从顶级数据结构访问值所需的键向量。
  • 递归遍历所有数据

  • 例子 :
    ;; not good since it takes `[k v]` as argument instead of `[path v]`, and is not recursive.
    user=> (clojure.walk/walk (fn [[k v]] [k (* 10 v)]) identity {:a 1 :b {:c 2}})
    ;; {:a 10, :c 30, :b 20}
    
    ;; it should receive as arguments instead :
    [[:a] 1]
    [[:b :c] 2]
    

    笔记:
  • 它也应该使用数组,使用键 0、1、2...(就像在 get-in 中一样)。
  • 我真的不在乎 outer参数,如果这允许简化代码。
  • 最佳答案

    目前正在学习 clojure,我尝试将此作为练习。
    然而,我发现直接实现它是非常棘手的,就像沿着树向下走一样应用内部函数。

    为了实现您正在寻找的结果,我将任务分为 2 个:

  • 首先将嵌套结构转换为以路径为键,值为
  • 的字典。
  • 然后映射内部函数,或者用外部函数减少。

  • 我的实现:
    ;; Helper function to have vector's indexes work like for get-in
    (defn- to-indexed-seqs [coll]
      (if (map? coll)
        coll
        (map vector (range) coll)))
    
    ;; Flattening the tree to a dict of (path, value) pairs that I can map over
    ;; user>  (flatten-path [] {:a {:k1 1 :k2 2} :b [1 2 3]})
    ;; {[:a :k1] 1, [:a :k2] 2, [:b 0] 1, [:b 1] 2, [:b 2] 3}
    (defn- flatten-path [path step]
      (if (coll? step)
        (->> step
             to-indexed-seqs
             (map (fn [[k v]] (flatten-path (conj path k) v)))
             (into {}))
        [path step]))
    
    ;; Some final glue
    (defn path-walk [f coll]
      (->> coll
          (flatten-path [])
          (map #(apply f %))))
    
    ;; user> (println (clojure.string/join "\n" (path-walk #(str %1 " - " %2) {:a {:k1 1 :k2 2} :b [1 2 3]})))
    ;; [:a :k1] - 1
    ;; [:a :k2] - 2
    ;; [:b 0] - 1
    ;; [:b 1] - 2
    ;; [:b 2] - 3
    

    关于dictionary - Clojure - 沿着路径行走,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594375/

    相关文章:

    c++ - 如何更改 map 容器的内部排序方案?

    python : Sort a dictionary by using keys in ascending order

    clojure - 如何在 Clojure 项目中安装依赖项

    clojure - Cascalog deffilterop 与纯 clojure

    python - 使用 JSON 文件中的信息创建字典

    Python:将字典附加到列表中

    c - C 中的线程 1 : EXC_BAD_ACCESS (code=1, 地址=0x0)

    data-structures - 用Rust进行交接锁定

    Java数据结构问题

    clojure - 在 Clojure 中按分隔符分割序列?