3

它在没有初始值的情况下工作:

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])但我想知道如何用累加器来实现它。

朱莉娅版本 1.1.1

4

1 回答 1

3

to的init参数reduce是关键字参数:

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
于 2019-06-11T21:08:33.897 回答