Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise reduce and use accumulator in Julia

Tags:

julia

It works without initial value:

reduce(+, [2 3 4])

Tried multiple ways to provide initial value - nothing works

reduce(+, [2 3 4], 1)
reduce(+, 1, [2 3 4])

Also seems like reduce could be used only with 2 argument operator. What function should be used to reduce collection with custom functions that accept current value and accumulator? Something like code below?

reduce((accumulator, value) -> push!(accumulator, value^2), [1, 2, 3], [])
# => [1, 4, 9]

This example could be implemented as map(x -> x^2, [1, 2, 3]) but I would like to know how to implement it as reduce with accumulator.

julia version 1.1.1

like image 241
Alex Craft Avatar asked Nov 02 '25 01:11

Alex Craft


1 Answers

The init argument to reduce is a keyword argument:

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
like image 66
Cameron Bieganek Avatar answered Nov 04 '25 02:11

Cameron Bieganek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!