In this particular case, cumsum does exactly this,

julia> cumsum([1:10])
10-element Array{Int64,1}:
  1
  3
  6
 10
 15
 21
 28
 36
 45
 55

I guess that would be idiomatic Julia ;)

An equivalent foldl would be
foldl((a, b) -> push!(a, a[end]+b), Int[1], [2:10])
10-element Array{Int64,1}:
  1
  3
  6
 10
 15
 21
 28
 36
 45
 55

A generic cumfoldl would be

julia> cumfoldl(f, x0, itr) = foldl((a, b) -> push!(a, f(a[end], b)),
[itr[1]], itr[2:end])
cumfoldl (generic function with 1 method)

julia> cumfoldl(*, 0, map(string, 1:10))
10-element Array{ASCIIString,1}:
 "1"
 "12"
 "123"
 "1234"
 "12345"
 "123456"
 "1234567"
 "12345678"
 "123456789"
 "12345678910"


I often find it useful to remind myself that foldl(push!, eltype(list)[],
list) constructs the same list and take it from there.

Reply via email to