Skip to content

clojure.core/reduce

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 25 Runnable: 22
([f coll] [f val coll])

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

by cody on
by jkkramer on
by ghoseb on . May have evaluation errors.
by devijvers on
by devijvers on
by gradysw on
by octopusgrabbus on
by octopusgrabbus on
by phreed on
by lwm on
by teymuri on
by teymuri on
by hadielmougy on
by sleyzerzon on . May have evaluation errors.
by cloxure on
by mahonbaldwin on
by phreed on
by ibercode on
by ibercode on
by ibercode on
by ftravers on . May have evaluation errors.
by tanrax on
by burinc on
by burinc on
by vasanth53 on

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


Content from the matching ClojureDocs page, with authors credited on each contribution.