clojure-italy

🇮🇹
2020-09-23T12:58:47.000300Z

ho scoperto reductions ieri

2020-09-23T12:59:08.000900Z

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

reborg 2020-09-23T13:47:59.002800Z

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

reborg 2020-09-23T13:49:40.003500Z

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