Is there a built-in proc which is equivalent to Python reduce or Javascript Array.reduce?
There are templates foldl and foldr in the sequtils module. Example:
import sequtils
proc factorial(n: int): int =
foldl(1..n, a * b, 1)
echo factorial(10)
As templates, they do not take proc arguments, but inline expressions, where a and b are the operands. The template works for any sort of collection that has an items iterator, such as arrays, sequences, or ranges (as in the above example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With