Clojure中smap术语是什么?官方文档相关含义解析
smap in Clojure? Great question! In Clojure's official documentation, smap is just a shorthand for substitution map—a regular Clojure map (or any map-like structure that implements the lookup protocol) used specifically for replacing elements in a collection.
Let’s break this down using the core/replace function you referenced:
- The
smapis the first argument you pass toreplace: it’s a set of key-value pairs where each key represents an element you want to swap out, and the corresponding value is what you want to replace it with. - Unlike a general-purpose map, when paired with
replace, thesmapacts purely as a lookup table for substitution operations.
Concrete example to illustrate:
If you run this code:
(replace {:a 1, :b 2} [:a :c :b :a])
The {:a 1, :b 2} here is the smap. The result will be [1 :c 2 1]—every occurrence of :a and :b gets replaced with their matching values from the smap, while elements not present as keys stay exactly as they are.
Another key point: smap isn’t a special built-in type or function in Clojure—it’s just a documentation term to describe a map being used for substitution. You can even use non-map structures here, like a vector (since vectors act as maps where indices are keys), as long as they support lookup operations.
For example, using a vector as an smap:
(replace [0 "one" "two"] [1 2 0 3])
This returns ["one" "two" 0 3], since the vector’s indices (1, 2, 0) map to their respective values in the substitution.
内容的提问来源于stack exchange,提问作者Philip

