reductions

added
1.2

ns
clojure.core

type
function

(reductions f coll) (reductions f init coll)

Returns a lazy seq of the intermediate values of the reduction (as
per reduce) of coll by f, starting with init.

                user=> (reductions + [1 1 1 1])
(1 2 3 4)
user=> (reductions + [1 2 3])
(1 3 6)

;; This is just like reduce except that the calculation is collected during the reduce.
user=> (assert (= (reduce + [1 2 3]) 
                  (last (reductions + [1 2 3]))))
nil

            
                user=> (reductions conj [] '(1 2 3))
([] [1] [1 2] [1 2 3])
            
                user=> (reductions + [1 2 3 4 5])
(1 3 6 10 15)

;;defining the function to perform the same reductions
user=> (reductions (fn [sum num] (+ sum num)) [1 2 3 4 5])
;;(1 3 6 10 15)

;;reductions using a init value 100
user=> (reductions (fn [sum num] (+ sum num)) 100 [1 2 3 4 5])
;;(100 101 103 106 110 115)

;;defining a function for the same reductions
user=>(defn add [sum num] 
    #_=>(+ sum num))
;;#'user/add

user=>(reductions add [1 2 3 4 5])
;;(1 3 6 10 15)
            
                ;; useful for performing lazy calculations which rely on 
;; previous calculations

;; e.g. Taking an infinite list of posts with some height and 
;; adding an offset to each, which is the sum of all previous 
;; heights

user=> (def posts (repeat {:height 50}))
#'user/posts

user=> (take 3 posts)
({:height 50} {:height 50} {:height 50})

user=> (def posts-with-offsets
  #_=>   (map #(assoc %1 :offset %2)
  #_=>        posts
  #_=>        (reductions + 0 (map :height posts))))
#'user/posts-with-offsets

user=> (take 3 posts-with-offsets)
({:height 50, :offset 0} {:height 50, :offset 50} {:height 50, :offset 100})