On Jun 17, 9:34 am, Wrexsoul <d2387...@bsnow.net> wrote:
> 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))))
>

Maybe "apply" can be used

user=> (apply + [1 2 3])
6
user=> (apply + [1 2 3 4 5])
15
user=> (defn tri [n] (accum + 0 (take n (iterate inc 1))))
#'user/tri
user=> (tri 10)
55
user=> (def inf (iterate inc 1))
#'user/inf
user=> (defn tri2 [n] (apply + (take n inf)))
#'user/tri2
user=> (tri2 10)
55
user=>

or "reduce"?
user=> (reduce + 0 [1 2 3])
6
user=> (reduce + 10 [1 2 3])
16
user=> (reduce + 0 [1 2 3 4 5])
15

Regards,
Parth

> 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