Fork me on GitHub
#clojure-italy
<
2020-09-23
>
andrea.crotti12:09:47

ho scoperto reductions ieri

andrea.crotti12:09:08

(reductions (fn [a b] (+ a b))
                  (range 10))
(0 1 3 6 10 15 21 28 36 45)

reborg13:09:59

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/)

reborg13:09:40

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])