Skip to content

Instantly share code, notes, and snippets.

@sogaiu
Last active March 15, 2025 12:46
Show Gist options
  • Save sogaiu/c6b015f0780e24c1bf408771966ef92f to your computer and use it in GitHub Desktop.
Save sogaiu/c6b015f0780e24c1bf408771966ef92f to your computer and use it in GitHub Desktop.
reduce-n
(defn reduce-n
[f init ind & inds]
(when (empty? inds)
(break (reduce f init ind)))
#
(var accum init)
(def n-inds (length inds))
(loop [[idx el] :pairs ind]
(set accum
(f accum el
;(seq [i :range [0 n-inds]]
(get-in inds [i idx])))))
#
accum)
(comment
# vanilla reduce
(reduce * 1 [2 3 5 7])
# =>
210
(reduce-n * 1 [2 3 5 7])
# =>
210
(reduce-n + 0 [1 2 3] [4 5 6])
# =>
21
(reduce-n * 1 [4 6 8] [6 9 12] [10 15 20])
# =>
373248000
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment