Skip to content

Instantly share code, notes, and snippets.

@kindlychung
Last active August 29, 2015 14:20
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 kindlychung/cd025ba6b79848cb2168 to your computer and use it in GitHub Desktop.
Save kindlychung/cd025ba6b79848cb2168 to your computer and use it in GitHub Desktop.
(defmacro areduce2 [f init xs]
`(let [xs# ~xs]
(loop [idx# 0 ret# ~init]
(if (< idx# (alength xs#))
(recur (unchecked-inc idx#) (~f ret# (aget xs# idx#)))
ret#))))
(areduce2 + 0 (int-array (range 100)))
(defn areduce1 [f init xs]
(loop [idx 0 ret init]
(if (< idx (alength xs))
(recur (unchecked-inc idx) (f init (aget xs idx)))
ret)))
(areduce1 + 0 (int-array (range 100)))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx, and return value named ret, initialized to init, setting ret to the evaluation of expr at each step, returning ret."
{:added "1.0"}
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx 0 ~ret ~init] (if (< ~idx (alength a#))
(recur (unchecked-inc ~idx) ~expr) ~ret))))
@kindlychung
Copy link
Author

(areduce1 + 0 (int-array (range 100)))
=> 99

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment