hgl has a "scan" function called sc
. What it does in general is a little bit abstract, so we will just talk about one specific way you can use it.
If we want to take a list of integers and get the partial sums of every prefix we can scan with +
for sums and 0
as a starting value:
ghci> sc (+) 0 [1,2,3,4,5,6]
[1,3,6,10,15,21]
This moves left to right adding each value of the list to the accumulator and replacing it with the sum.
We can also scan things other than lists. We can scan all sorts of trees and list-like things. hgl more or less builds the scan function based on the type we give it.
One weirder example is ragged lists. These are lists that contain a mixture of values and other ragged lists. For example:
[1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2]
The compiler has dreamed up a rather weird way to scan these. When the list contains values it behaves normally:
ghci> sc (+) 0 [1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2]
[1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2]
^1
[1,3,3,[2,3,4],[],2,1,[4,8,[6],5],2]
^3
[1,3,6,[2,3,4],[],2,1,[4,8,[6],5],2]
^6
but when it hits a list it splits the read head in two. One goes down that list and scans it, the other skips it and scans the rest of the outer list.
[1,3,6,[8,3,4],[],2,1,[4,8,[6],5],2]
^6
[1,3,6,[8,3,4],[],2,1,[4,8,[6],5],2]
^8 ^6
[1,3,6,[8,11,4],[],8,1,[4,8,[6],5],2]
^11 ^8
[1,3,6,[8,11,15],[],8,9,[4,8,[6],5],2]
^15 ^9
[1,3,6,[8,11,15],[],8,9,[4,8,[6],5],2]
^9
[1,3,6,[8,11,15],[],8,9,[13,8,[6],5],11]
^13 ^11
[1,3,6,[8,11,15],[],8,9,[13,21,[6],5],11]
^21
[1,3,6,[8,11,15],[],8,9,[13,21,[6],5],11]
^21
[1,3,6,[8,11,15],[],8,9,[13,21,[27],26],11]
^27 ^26
[1,3,6,[8,11,15],[],8,9,[13,21,[27],26],11]
This treats a ragged list as a sort of tree, where the main list forms a spine and each nested list is an offshoot from that spine.
Task
Take a ragged list of positive integers as input and perform the scan shown above (sc (+) 0
) returning the scanned list.
You may take and output a ragged list in any reasonable format.
This is code-golf so answers will be scored in bytes with minimizing the source size being the goal.
Test cases
[] -> []
[8] -> [8]
[1,2,3] -> [1,3,6]
[1,1,1,1,1] -> [1,2,3,4,5]
[[1],[1],[1]] -> [[1],[1],[1]]
[1,[1],[1],[1]] -> [1,[2],[2],[2]]
[1,2,3,[2,3,4],[],2,1,[4,8,[6],5],2] -> [1,3,6,[8,11,15],[],8,9,[13,21,[27],26],11]
[[1,2,3,4],[1,2,3],[1,2,3]] -> [[1,3,6,10],[1,3,6],[1,3,6]]
null
in place of empty sub-arrays? \$\endgroup\$