I'm shocked that this is missing from clojure.core:

(defn accum [f init coll]
  (loop [x init c coll]
    (if (empty? c)
      x
      (recur (f x (first c)) (rest c)))))

user=> (accum + 0 [1 2 3])
6
user=> (accum + 0 [1 2 3 4 5])
15

This is one of the most basic, useful functions in functional
programming. :)

Here's any triangular number:

(defn tri [n] (accum + 0 (take n (iterate inc 1))))

Here's a lazy seq of them all:

(def *tris* (for [i (iterate inc 1)] (tri i)))

This, however, is more efficient (and demonstrates another case where
super-lazy-seq makes something very compact and readable):

(defn accum-map [f init coll]
  (super-lazy-seq [x init c coll]
    (if (seq c)
      (next-item x (f x (first c)) (rest c)))))

(def *tris* (rest (accum-map + 0 (iterate inc 1))))

Notice how similar the accum-map code is to the accum code? With just
lazy-seq it would not be as clear. :)

The "rest" in the replacement def for *tris* is because accum-map
returns the init value as the first value of the sequence, i.e., it's
equivalent to making a sequence of (tri 0), (tri 1), (tri 2), and so
on.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to