Skip to content

Instantly share code, notes, and snippets.

@mecdemort
Created March 10, 2011 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mecdemort/a5a7b994cdb3774e1843 to your computer and use it in GitHub Desktop.
Save mecdemort/a5a7b994cdb3774e1843 to your computer and use it in GitHub Desktop.
(defn accumulate1
"accumulate a collection of terms from a to b using a combiner function"
([combiner init term a next b]
(->> (iterate next a)
(take-while #(<= % b) ,)
(map term ,)
(reduce combiner init ,))))
(defn accumulate2
"accumulate a collection of terms from a to b using a combiner function"
([combiner init term a next b]
(reduce combiner init
(for [x (iterate next a)
:while (<= x b)]
(term x)))))
(defn accumulate3
"accumulate a collection of terms from a to b using a combiner function"
([combiner init term a next b]
(loop [a a, result init]
(if (> a b)
result
(recur (next a) (combiner result (term a)))))))
(defn summation
"sum f(n) from 0 to n-1"
([f n] (accumulate1 + 0 f 0 inc (dec n))))
(defn e**x [x n]
(sumation #(/ (Math/pow x %) (factorial %)) n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment