Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of reduce in nim?

Tags:

nim-lang

Is there a built-in proc which is equivalent to Python reduce or Javascript Array.reduce?

like image 761
Jundiaius Avatar asked Oct 19 '25 06:10

Jundiaius


1 Answers

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).

like image 151
Reimer Behrends Avatar answered Oct 20 '25 20:10

Reimer Behrends