liveBook · Manning

Merge-with

As explained in Clojure: The Essential Reference

merge-with is a Clojure function that combines maps while applying a supplied function to values associated with conflicting keys.

merge-with combines one or more maps and resolves repeated keys with a supplied two-argument function. For each conflict, the function receives the current value and the incoming value; its result replaces both. section 11.3.3

Use it when collisions represent aggregation rather than simple replacement:

  • Sum numeric values with (merge-with + {:a 1} {:a 10 :b 2}), producing {:a 11, :b 2}. section 11.3.3
  • Concatenate collections with (merge-with into m1 m2 m3), accumulating values for each repeated key. section 11.3.3
  • Provide a custom function when values have mixed shapes, such as preserving an existing vector before conjoining later values. section 11.3.3
(merge-with + {:a 1} {:b 2 :a 10}) ; #1
;; {:a 11, :b 2}

A compact executable example shows conflict resolution alongside an ordinary, nonconflicting key. section 11.3.3

The first input map determines the output type, although an array-map can promote to a hash-map. Nil-only calls return nil; a single non-nil argument returns itself. Map inputs are supported, while sequential inputs can produce incorrect nested structures; sorted maps require comparable keys. section 11.3.3

How Clojure: The Essential Reference covers it

How deep it goes
Defines the contract, return behavior, output types, edge cases, and custom aggregation examples without detailing implementation internals.
Examples
Demonstrates numeric addition, sequence accumulation, heterogeneous values, product transformation, and complex-number addition.
What it assumes
Assumes familiarity with Clojure maps, functions, and common collection operations.
What you can do after
Apply it via Clojure to combine maps using a chosen conflict-resolution function.
How it connects
Connects map merging with merge, sorted maps, records, protocols, and collection aggregation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.