ho scoperto reductions ieri
(reductions (fn [a b] (+ a b))
(range 10))
(0 1 3 6 10 15 21 28 36 45)
eh eh, ha degli usi spettacolari, tipo una soluzione del trapped-water problem che aveva postato @skuro :
(defn trapped-water [towers]
(let [maxes #(reductions max %) ; the seq of increasing max values found in the input seq
maxl (maxes towers) ; the seq of max heights to the left of each tower
maxr (reverse (maxes (reverse towers))) ; the seq of max heights to the right of each tower
mins (map min maxl maxr)] ; minimum highest surrounding tower per position
(reduce + (map - mins towers)))) ; sum up the trapped water per position
(reference: https://www.geeksforgeeks.org/trapping-rain-water/)un altro classico, la moving-average:
(defn next-average [[cnt sum avg] x]
(let [new-cnt (inc cnt)
new-sum (+ sum x)
new-avg (/ new-sum (double new-cnt))]
[new-cnt new-sum new-avg]))
(defn stock-prices [values]
(reductions next-average [0 0 0] values))
(stock-prices [5.4 3.4 7 8.2 11])