如何在Clojure中将Map中的所有值x替换为y?
Solution for Replacing Values in a Clojure Map
Here's an idiomatic, straightforward implementation of your desired function:
(defn change-x-to-y-in-map [m x y] (reduce-kv (fn [acc k v] (assoc acc k (if (= v x) y v))) {} m))
How this works:
- We use
reduce-kv(reduce with key-value pairs)—this is the go-to tool for iterating over Clojure maps, as it gives direct access to each key and value without extra conversion steps. - For every entry in the input map:
- We check if the current value
vmatches the targetx. - If there's a match, we substitute it with
y; otherwise, we keep the original value. - We build up a new map incrementally: starting with an empty map
{}, we useassocto add each updated key-value pair to the accumulator (acc).
- We check if the current value
Testing with your example:
Run this code with your sample input:
(change-x-to-y-in-map {:a 1 :b 2 :c 1} 1 "it works!")
You'll get the exact result you're looking for:
{:a "it works!", :b 2, :c "it works!"}
Alternative approach (using map and into):
If you prefer a more sequence-focused style, this version works too—maps in Clojure are treated as sequences of key-value vectors, so we can transform them directly:
(defn change-x-to-y-in-map [m x y] (into {} (map (fn [[k v]] [k (if (= v x) y v)]) m)))
Here, we map over each key-value pair to update values as needed, then use into {} to convert the transformed sequence back into a map. Both approaches are valid; the reduce-kv version is slightly more efficient for larger maps, but either is perfectly idiomatic.
内容的提问来源于stack exchange,提问作者Ville Lehtonen
相关产品推荐
相关产品推荐

