Clojure中实现合并两个map向量的函数:同车型取最低价格
Solution for Merging Car Maps by Minimum Price
Alright, let's solve this problem where we need to merge two vectors of Clojure maps, keeping only the entry with the lowest :price for each :car value. Here's how to approach it step by step:
First, let's recap the requirements clearly:
- We have two vectors of maps, each containing
:id,:car, and:pricekeys - For entries with the same
:carvalue, we keep the one with the smallest:price - All unique
:carentries (no duplicates across inputs) should be retained as-is
Step-by-Step Approach
- Combine both input vectors: Merge all entries into a single sequence so we can process them uniformly.
- Group entries by
:car: Cluster all maps that share the same car type together. - Select the minimum price entry per group: For each car group, pick the map with the lowest
:pricevalue. - Optional: Sort by
:car: If you want the output ordered alphabetically by car type (matching your expected output), add a sort step.
Clojure Code Implementation
First, define your input vectors:
(def input1 [{:id 1 :car "A" :price 10} {:id 2 :car "B" :price 20} {:id 3 :car "C" :price 30}]) (def input2 [{:id 4 :car "A" :price 5} {:id 5 :car "B" :price 30} {:id 6 :car "D" :price 40}])
Then the merging function:
(defn merge-car-maps [first-maps second-maps] (->> (concat first-maps second-maps) (group-by :car) (map (fn [[_ car-group]] (apply min-key :price car-group))) (sort-by :car)))
Testing the Function
When you call the function with your inputs:
(merge-car-maps input1 input2)
You'll get exactly the expected output:
[{:id 4, :car "A", :price 5} {:id 2, :car "B", :price 20} {:id 3, :car "C", :price 30} {:id 6, :car "D", :price 40}]
How It Works
concat: Merges the two input vectors into one continuous sequence of maps.group-by :car: Creates a map where each key is a car type (like "A"), and the value is a vector of all maps with that car type.min-key :price: This function takes a key (:price) and a collection, returning the element with the smallest value for that key. Usingapplyhere passes all elements of the car group tomin-key.sort-by :car: Sorts the final collection alphabetically by the:carkey to match the order in your expected output. If you don't care about the order, you can omit this step.
内容的提问来源于stack exchange,提问作者Kami.Foo
相关产品推荐
相关产品推荐

