简体   繁体   English

Clojure:根据另一个集合查找集合中丢失的记录

[英]Clojure: Find missing records in a collection based on another collection

I have 2 vectors: employ and emp-income.我有 2 个向量:employ 和 emp-income。 I want to loop thru emp-income based on employ to find what all the missing records.我想通过基于雇佣的 emp-income 循环查找所有丢失的记录。 In this case, it's missing id = 2. And i want to create the missing record in emp-income and set the income as the previous record's income value.在这种情况下,它缺少 id = 2。我想在 emp-income 中创建缺少的记录并将收入设置为以前记录的收入值。 What is the best way to do it in clojure?在clojure中做到这一点的最佳方法是什么?

(def employ
  [{:id 1 :name "Aaron"}
   {:id 2 :name "Ben"}
   {:id 3 :name "Carry"}])

from:从:

(def emp-income
  [{:emp-id 1 :income 1000}
   {:emp-id 3 :income 2000}])

to:到:

 (def emp-income
      [{:emp-id 1 :income 1000}
       {:emp-id 2 :income 1000}
       {:emp-id 3 :income 2000}])

You could use:你可以使用:

(let [emp-id->income (into {} (map (fn [rec] [(:emp-id rec) rec]) emp-income))]
    (reduce (fn [acc {:keys [id]}]
                   (let [{:keys [income]} (or (get emp-id->income id) (peek acc))]
                     (conj acc {:emp-id id :income income})))
                 []
                 employ))

Note this will create a record of {:emp-id id :income nil} if the first record is not found in emp-income .请注意,如果在emp-income找不到第一条记录,这将创建一个{:emp-id id :income nil}记录。 It will also use the last :emp-id encountered if duplicate :emp-id values are found within emp-income .它也将使用最后:emp-id遇到重复是否:emp-id值内发现的emp-income

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM