4clojure #60 Sequence Reductions

4clojure #60 Sequence Reductions

reduceのような動きをする関数を書く。 ただし、縮小する各中間の値を返すこと。 2か3引数をとり、遅延シーケンスを返すこと。

reductions使用禁止

reductionsを使えばそのまま解決できました。

(= (take 5 (__ + (range))) [0 1 3 6 10])
(= (__ conj [1] [2 3 4]) [[1] [1 2] [1 2 3] [1 2 3 4]])
(= (last (__ * 2 [3 4 5])) (reduce * 2 [3 4 5]) 120)
(take 5 (
(fn my-reductions
  ([f coll]
     (lazy-seq
      (if-let [s (seq coll)]
        (my-reductions f (first s) (rest s))
        (list (f)))))
  ([f init coll]
     (cons init
           (lazy-seq
            (when-let [s (seq coll)]
              (my-reductions f (f init (first s)) (rest s)))))))
 + (range)))
参考 reductionsの定義
(defn reductions
  "Returns a lazy seq of the intermediate values of the reduction (as
  per reduce) of coll by f, starting with init."
  {:added "1.2"}
  ([f coll]
     (lazy-seq
      (if-let [s (seq coll)]
        (reductions f (first s) (rest s))
        (list (f)))))
  ([f init coll]
     (cons init
           (lazy-seq
            (when-let [s (seq coll)]
              (reductions f (f init (first s)) (rest s)))))))