You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 v matches the target x.
    • 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 use assoc to add each updated key-value pair to the accumulator (acc).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:12:53