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.
(reduce + [1 2 3 4 5]) ;;=> 15 (reduce + []) ;;=> 0 (reduce + [1]) ;;=> 1 (reduce + [1 2]) ;;=> 3 (reduce + 1 []) ;;=> 1 (reduce + 1 [2 3]) ;;=> 6
;; Create a word frequency map out of a large string s. ;; `s` is a long string containing a lot of words :) (reduce #(assoc %1 %2 (inc (%1 %2 0))) {} (re-seq #"\w+" s)) ; (This can also be done using the `frequencies` function.)
;; Calculate primes until 1000 (reduce (fn [primes number] (if (some zero? (map (partial mod number) primes)) primes (conj primes number))) [2] (take 1000 (iterate inc 3))) ;;=> [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 ;; 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 ;; 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 ;; 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 ;; 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 ;; 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 ;; 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 ;; 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 ;; 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 ;; 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 ;; 991 997]
;; Add one collection to another (combining sequences is done with cons): (reduce conj [1 2 3] [4 5 6]) ;;=> [1 2 3 4 5 6] (reduce #(cons %2 %1) [1 2 3] [4 5 6]) ;;=> '(6 5 4 1 2 3)
;; Combine a vector of collections into a single collection ;; of the type of the first collection in the vector. (reduce into [[1 2 3] [:a :b :c] '([4 5] 6)]) ;;=> [1 2 3 :a :b :c [4 5] 6] ;; The flatten function can be used to completely fuse ;; all of the items of a nested tree into a single sequence. ;; Sometimes all that is needed is to fuse the first level ;; of a tree. This can be done with 'reduce' and 'into'. (reduce into [] '([] [[10 18]] [[8 18]] [[10 12]] [[0 -6]] [[2 6]])) ;;=> [[10 18] [8 18] [10 12] [0 -6] [2 6]]
(defn key-pres? "This function accepts a value (cmp-val) and a vector of vectors (parsed output from clojure-csv) and returns the match value back if found and nil if not found. Using reduce, the function searches every vector row to see if cmp-val is at the col-idx location in the vector." [cmp-val cmp-idx csv-data] (reduce (fn [ret-rc csv-row] (if (= cmp-val (nth csv-row col-idx nil)) (conj ret-rc cmp-val))) [] csv-data))
(defn reduce-csv-row "Accepts a csv-row (a vector) a list of columns to extract, and reduces (and returns) a csv-row to a subset based on selection using the values in col-nums (a vector of integer vector positions.)" [csv-row col-nums] (reduce (fn [out-csv-row col-num] ; Don't consider short vectors containing junk. (if-not (<= (count csv-row) 1) (conj out-csv-row (nth csv-row col-num nil)))) [] col-nums))
;; Some functions update a collection with a single item. ;; A number of functions have a 'more' argument which lets ;; them work over collections. ;; These functions can benefit 'reduce' which lets them work ;; a collection of items... (into {} {:dog :food}) (reduce into {} [{:dog :food} {:cat :chow}]) ;;=> {:dog :food, :cat :chow}
;; The reduction will terminate early if an intermediate result uses the ;; `reduced` function. (defn limit [x y] (let [sum (+ x y)] (if (> sum 10) (reduced sum) sum))) (reduce + 0 (range 10)) ;; => 45 (reduce limit 0 (range 10)) ;; => 15
;; This will generate the first 100 Fibonacci numbers ;; (size of (range) + 2): (reduce (fn [a b] (conj a (+' (last a) (last (butlast a))))) [0 1] (range 98)) ;; [0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881 6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120 4660046610375530309 7540113804746346429 12200160415121876738N 19740274219868223167N 31940434634990099905N 51680708854858323072N 83621143489848422977N 135301852344706746049N 218922995834555169026N]
;; Reduce can be used to reimplement a map function: (defn map* [f & c] (let [c* (partition (count c) (apply interleave c))] (reduce (fn [s k] (conj s (apply f k))) [] c*))) ;; user=> (map* * [0.5 0.5 0.5] (range)) ;; [0.0 0.5 1.0] ;; user=> (map* str "clojure" (range)) ;; ["c0" "l1" "o2" "j3" "u4" "r5" "e6"]
;; Update map entries: (defn update-map-entries [m e] (reduce #(update-in %1 [(first %2)] (fn [_] (last %2))) m e)) ;; => (update-map-entries {:a 1 :b 2 :c 3} {:a 5 :b 9}) ;; {:a 5, :b 9, :c 3} ;; => (update-map-entries {:a 1 :b 2 :c 3} {:a 5 :b 9 :d 8}) ;; {:a 5, :b 9, :c 3, :d 8}
;; Flatten values in a map. (reduce (fn [flattened [k v]] (clojure.set/union flattened v)) #{} {:e #{:m :f}, :c #{:f}, :b #{:c :f}, :d #{:m :f}, :a #{:c :f}}) ;; => #{:m :c :f}
;; Reduce over maps by destructuring keys: (def x {:a 1 :b 2}) (reduce (fn [p [k v]] (into p {k (+ 1 v)})) {} ; First value for p x) ;; => {:a 2, :b 3}
;; conj! over transient array for speed. ;; This example flattens over one level. ;; To do so uses reduce twice. (persistent! (reduce (fn [acc0 item-vector] (reduce (fn [acc1 item] (conj! acc1 item)) acc0 item-vector)) (transient []) [[:foo :bar :baz] [] [:fred :barney]])) ;;=> [:foo :bar :baz :fred :barney]
;;reduce with side effects ;;given a collection return a new collection (def initial-coll [1 2 3 4 5]) (defn byten [coll] (reduce (fn [new-coll unit] (into new-coll [(* 10 unit)])) [] coll)) (byten initial-coll) ;;[10 20 30 40 50]
;; Reduce with side effects using an anonymous function ;; given a collection return a new collection: (def initial-coll [1 2 3 4 5]) (defn byten [coll] (reduce #(into %1 [(* 10 %2)]) [] coll)) (byten initial-coll) ;; => [10 20 30 40 50]
;; A practical example of mapping over values ;; in a hash-map with the `upper-case` function: (reduce (fn [acc [k v]] (assoc acc k (clojure.string/upper-case v))) {} {:a "aaaaaaa" :b "bbbbbbb"}) ;; => {:a "AAAAAAA", :b "BBBBBBB"}
(reduce (fn [accumulator current-item] ; <-- accumulator is FIRST argument to function ...) ; <-- your fn definition goes here [] ; <-- initial value for your accumulator [:a :b]) ; <-- collection to operate on
(reduce #(str %1 %2) "" ["Woody" "Potato" "Buzz"]) ;;=> "WoodyPotatoBuzz" ;; or (reduce (fn [accumulator current-item] (str accumulator current-item)) "" ["Woody" "Potato" "Buzz"]) ;;=> "WoodyPotatoBuzz"
; Nice use of reduce from some version of medley library ; https://github.com/weavejester/medley (defn assoc-some "Associates a key k, with a value v in a map m, if and only if v is not nil." ([m k v] (if (nil? v) m (assoc m k v))) ([m k v & kvs] (reduce (fn [m [k v]] (assoc-some m k v)) (assoc-some m k v) (partition 2 kvs)))) (assoc-some {} :a 1) ;;=> {:a 1} (assoc-some {} :a nil :b 2) ;;=> {:b 2} (assoc-some {:a 1 :b 2} :a 10 :c 3) ;;=> {:a 10, :b 2, :c 3}
;; Transform key/value pairs (reduce (fn [acc [k v]] (assoc acc (str (name k)) v)) {} [[:a 1] [:b 2] [:c 3]]) ;;=> {"a" 1, "b" 2, "c" 3} (reduce (fn [acc [k v]] (assoc acc (str "k" k) (* v 2))) {} (partition 2 (range 10))) ;;=> {"k0" 2, "k2" 6, "k4" 10, "k6" 14, "k8" 18}
Returns a lazy seq of the intermediate values of the reduction (as per reduce) of coll by f, start...
Applies fn f to the argument list formed by prepending intervening arguments to args.
Returns a map from distinct items in coll to the number of times they appear.
Wraps x in a way such that a reduce will terminate with the value x
Reduces an associative collection. f should be a function of 3 arguments. Returns the result of ap...
Reduces a collection using a (potentially parallel) reduce-combine strategy. The collection is par...
Applies f to each value in coll, splitting it each time f returns a new value. Returns a lazy se...
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.