Warm tip: This article is reproduced from serverfault.com, please click

clojure-将转导输出与输入组合到哈希图中

(clojure - Combine transduction output with input into a hashmap)

发布于 2020-12-01 10:27:37

我想在Clojure中尽可能地做到以下几点:

  1. 转换集合
  2. 将输入集合的每个元素与输出集合中的对应元素相关联
  3. 在哈希图中返回结果

是否有使用核心库函数的简洁方法?

如果没有,你可以建议对以下实现进行哪些改进?

(defn to-hash [coll xform]
  (reduce
    merge
    (map
      #(apply hash-map %)
      (mapcat hash-map coll (into [] xform coll)))))
Questioner
Eureton
Viewed
11
leetwinski 2020-12-01 19:50:18

像这样的事情应该在没有中间集合的情况下达到目的:

(defn process [data xform]
  (zipmap data (eduction xform data)))

user> (process [1 2 3] (comp (map inc) (map #(* % %))))
;;=> {1 4, 2 9, 3 16}

有关教育的文档说以下内容:

返回转换器对coll中项目的可还原/可迭代应用。换能器按顺序应用,就好像与comp组合一样。注意,每次调用reduce / iterator时,将执行这些应用程序。

因此不会创建其他集合。

当然,只要输入和输出元素之间存在一对一的关系,这就是任何好处。(process [1 -2 3] (filter pos?))所需的输出是(process [1 1 1 2 2 2] (dedupe))什么?

(顺便说一下,你的to-hash实现具有相同的缺陷)