3

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

Jundiaius
  • 6,214
  • 3
  • 30
  • 43

1 Answers1

5

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

Reimer Behrends
  • 8,600
  • 15
  • 19
  • 2
    The fact that I can't use an anonymous `proc` as an argument but only an inline expression with operands does make nim much less functional-programming-friendly, doesn't it? – Jundiaius Aug 22 '18 at 14:27
  • 1
    Well your inline expression can be `doSomething(a, b)` or even `somethingElse(b, 10, a+b, nested(b))`. Basically what it does is to stamp out whatever it is you put there into the body of the loop that it creates. This means you can use anything there, not only procedures with a certain signature. To achieve the same thing in Python you would need to use a wrapper function, but function calls aren't free so you will be adding overhead, this is both easier and more efficient. I'd say Nim is actually more functional friendly, just take a look at e.g. https://github.com/zero-functional – PMunch Aug 23 '18 at 07:35
  • 1
    @PMunch you can't really be functional-friendly if you're not using functions e.g., in a functional-friendly `foldl` you could do this: `foldl(1..n, `*`, 1)`. – Yawar Oct 14 '18 at 03:30