Skip to content
Browse files

New post

  • Loading branch information...
1 parent 06c8566 commit 15350054619dbea1bbc4e062c5c2b8b9b50616e3 @djhworld committed Mar 6, 2012
Showing with 19 additions and 3 deletions.
  1. +19 −3 _posts/2012-03-06-reduce-reduce.md
View
22 _posts/2012-03-06-reduce-reduce.md
@@ -19,7 +19,7 @@ Clojure standard libraries)
{% highlight clojure %}
(reduce + 0 (range 10))
- ;=> 55
+ ;=> 45
{% endhighlight %}
But what does this actually mean? What is going on here? Well to gain
@@ -33,7 +33,7 @@ breaking the problem down and implementing it myself.
accumulator
(recur (+ accumulator (first coll)) (rest coll)))))
;=> (my-sum (range 10))
- ;=> 55
+ ;=> 45
{% endhighlight %}
So in effect, my implementation sets up an *accumulator* (starting at
@@ -50,6 +50,22 @@ accumulator, a sequence, a function that takes the accumulator and the
first item of the sequence and a loop that moves through the rest
until the sequence has been consumed.
+Perhaps we can use the above code and make it more generic and
+re-usable
+
+{% highlight clojure %}
+ (defn consume-sequence [f accumulator coll]
+ (loop [accumulator accumulator coll coll]
+ (if (empty? coll)
+ accumulator
+ (recur (f accumulator (first coll)) (rest coll)))))
+
+ ;=> (consume-sequence + 0 (range 10))
+ ;=> 45
+ ;=> (consume-sequence * 1 [1 2 3 4 5])
+ ;=> 120
+{% endhighlight %}
+
This is in essence what ```reduce``` does. While the underlying
code in Clojure may be different and more efficient, the core
concepts described above are generally the same. So if we translate
@@ -81,7 +97,7 @@ Seeing as ```+``` accepts multiple arguments, we can just pass that instead.
How about that ```my-product``` function?
{% highlight clojure %}
- (reduce * 0 (range 10))
+ (reduce * 1 [1 2 3 4 5])
{% endhighlight %}
The accumulator doesn't have to be a number either, it can be anything

0 comments on commit 1535005

Please sign in to comment.
Something went wrong with that request. Please try again.