Search code examples
nim-lang

What is the equivalent of reduce in nim?


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


Solution

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