它在没有初始值的情况下工作:
reduce(+, [2 3 4])
尝试了多种方式来提供初始值 - 没有任何效果
reduce(+, [2 3 4], 1)
reduce(+, 1, [2 3 4])
而且 reduce 似乎只能与 2 个参数运算符一起使用。应该使用什么函数来减少接受当前值和累加器的自定义函数的集合?类似下面的代码?
reduce((accumulator, value) -> push!(accumulator, value^2), [1, 2, 3], [])
# => [1, 4, 9]
这个例子可以实现为 map(x -> x^2, [1, 2, 3])
但我想知道如何使用累加器将其实现为 reduce。
julia 版本 1.1.1
最佳答案
reduce
的init
参数是关键字参数:
julia> reduce(+, [2 3 4], init = 1)
10
julia> reduce((accumulator, value) -> push!(accumulator, value^2), [1, 2, 3], init = [])
3-element Array{Any,1}:
1
4
9
关于julia - 如何在 Julia 中初始化 reduce 和使用累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56551418/