liveBook · Manning

Clojure.data/diff

As explained in Clojure: The Essential Reference

clojure.data/diff is a Clojure function that recursively compares two values and returns the parts unique to each value and the parts they share.

clojure.data/diff recursively compares two values and reports what belongs only to the first value, only to the second, and to both. Unlike =, which returns only a boolean, diff describes how nested data differs. section 6.7 section 6.0

Call diff with exactly two values:

  • Returns [only-in-a only-in-b common] when the inputs have compatible types and share some structure. section 6.7
  • Returns [a b nil] when the values share nothing or have incompatible types. section 6.7
  • Compares maps, lists, vectors, sets, Java arrays, and scalar values, using compatibility rules for each category. section 6.7
  • Raises ArityException unless exactly two arguments are supplied; deeply nested structures can also exhaust the stack. section 6.7

Comparing nested configuration

(diff {:a "1" :b "2"} {:b "2" :c "4"}) ;; ({:a "1"} {:c "4"} {:b "2"}) (diff [1 {:a [1 2]}] [1 {:a [1 3]}]) ;; [[nil {:a [nil 2]}] ;; [nil {:a [nil 3]}] ;; [1 {:a [1]}]] The third element preserves the common nested structure, while the first two isolate each side's changes.

Turning a diff into paths

The first result can be walked recursively to locate changed keys. For two service configurations, diff-to-path produces paths such as [:profiles :dev :dependencies :dep8] and [:profiles :uberjar :aot], which can then guide get-in or targeted updates.

How Clojure: The Essential Reference covers it

How deep it goes
Defines inputs, triplet outputs, compatibility rules, exceptions, nested examples, path extraction, and deep-stack limits.
Examples
Demonstrates maps, nested vectors and maps, numbers, sets, Java arrays, incompatible maps, and service-configuration changes.
What it assumes
Assumes familiarity with Clojure equality, collections, nested maps, and basic functions such as get-in.
What you can do after
Diagnose/debug with it by isolating changed values and converting nested differences into navigable key paths.
How it connects
Connects Clojure equality, nested data structures, maps, vectors, sets, Java arrays, and configuration paths.

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.