clojure.core/reduce¶
f should be a function of 2 arguments. If val is not supplied, returns the result of applying f to the first 2 items in coll, then applying f to that result and the 3rd item, etc. If coll contains no items, f must accept no arguments as well, and reduce returns the result of calling f with no arguments. If coll has only 1 item, it is returned and f is not called. If val is supplied, returns the result of applying f to val and the first item in coll, then applying f to that result and the 2nd item, etc. If coll contains no items, returns val and f is not called.
Examples¶
Note by JoshuaEckroth¶
clojure.core/reduce seems to be a special case of a function that's defined twice in core.clj, and the first definition (at the line cited above: 773) is just a temporary definition; the real definition is later at line 5323, which contains the docstring.
Note by didibus¶
The reducing function f is of shape:
(f [accumulator next-element] ...)
Note by iljaf¶
The 4th example (generating prime numbers) is kind of nice conceptually, but running it for the first 1m integers is taking 2 min on i7 2.7GHz machine, so it seems to be a very inefficient way of generating prime numbers.
See also¶
- clojure.core/reductions (2)
- clojure.core/apply (14)
- clojure.core/frequencies (2)
- clojure.core/reduced (3)
- clojure.core/reduced?
- clojure.core/reduce-kv (1)
- clojure.core.reducers/fold (0)
- clojure.core/partition-by (3)
Content from the matching ClojureDocs page, with authors credited on each contribution.