julia - 如何在 Julia 中初始化 reduce 和使用累加器

标签 julia

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

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

最佳答案

reduceinit 参数是关键字参数:

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/

相关文章:

julia - 一个包中有 2 个模块是不是很糟糕?

julia - 在 Julia 中预分配已知大小的数据框

performance - 广播分配慢 Julia

dataframe - 尝试使用 Arrow.jl 保存 DataFrame 给出 : ArgumentError: type does not have a definite number of fields. 整数元组的元组

arrays - Julia - 将矩阵转换为向量

random - 在 Julia 中生成范围内的随机整数

oop - Julia 中的享元/OOP 设计模式

r - R 中的抽象类型

python - 用于将字符串转换为 Snake_case/CamelCase 的 Julia 实现

在 Julia 中保存数据