Flatten a list: Difference between revisions

m
Line 2,089:
flat(arr) = mapreduce(x -> x == [] || x[1] === x ? x : flat(x), vcat, arr, init=[])
</lang>
An iterative recursive version that uses less memory but is slower:
<lang julia>function flat1(arr)
rst = Any[]
Line 2,098:
rst
end
</lang>
Using the Julia standard Iterators library:
<lang julia>
flat2(arr) = (while any(a -> a isa Vector, arr) arr = collect(Iterators.flatten(arr)) end; arr)
 
arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Line 2,103 ⟶ 2,107:
@show flat(arr)
@show flat1(arr)
@show flat2(arr)
 
@btime flat(arr)
@btime flat1(arr)
@btime flat2(arr)
</lang>{{out}}
<pre>
flat(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat1(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat2(arr) = [1, 2, 3, 4, 5, 6, 7, 8]
18.501 μs (193 allocations: 9.44 KiB)
49517.871200 nsμs (5193 allocations: 2569.44 bytesKiB)
504.145 ns (5 allocations: 256 bytes)
1836.501699 μs (193106 allocations: 93.4473 KiB)
</pre>
 
4,108

edits