nim 中 reduce 的等价物是什么?
What is the equivalent of reduce in nim?
是否有内置的proc
相当于Pythonreduce
或JavascriptArray.reduce
?
sequtils
模块中有模板 foldl
和 foldr
。示例:
import sequtils
proc factorial(n: int): int =
foldl(1..n, a * b, 1)
echo factorial(10)
作为模板,它们不接受 proc 参数,而是内联表达式,其中 a
和 b
是操作数。该模板适用于具有 items
迭代器的任何类型的集合,例如数组、序列或范围(如上例所示)。
是否有内置的proc
相当于Pythonreduce
或JavascriptArray.reduce
?
sequtils
模块中有模板 foldl
和 foldr
。示例:
import sequtils
proc factorial(n: int): int =
foldl(1..n, a * b, 1)
echo factorial(10)
作为模板,它们不接受 proc 参数,而是内联表达式,其中 a
和 b
是操作数。该模板适用于具有 items
迭代器的任何类型的集合,例如数组、序列或范围(如上例所示)。