Flatten a list: Difference between revisions
Content added Content deleted
(Flatten a list in XBasic) |
(→{{header|Julia}}: Interpolate variable from global scope, as required for accurate benchmarking; more idiomatic style) |
||
Line 2,226: | Line 2,226: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Note that Julia versions prior to 0.5 |
(Note that Julia versions prior to 0.5 automatically flattened nested arrays.) |
||
⚫ | |||
The following version of flatten makes use of the higher order function ''mapreduce''. |
|||
flat(arr) = mapreduce(x -> x == [] || x[1] === x ? x : flat(x), vcat, arr, init=[]) |
|||
<lang julia>isflat(x) = isempty(x) || first(x) === x |
|||
⚫ | |||
function flat_mapreduce(arr) |
|||
mapreduce(vcat, arr, init=[]) do x |
|||
isflat(x) ? x : flat(x) |
|||
end |
|||
⚫ | |||
An iterative recursive version that uses less memory but is slower: |
An iterative recursive version that uses less memory but is slower: |
||
<lang julia>function |
<lang julia>function flat_recursion(arr) |
||
res = [] |
|||
grep(v) |
function grep(v) |
||
for x in v |
|||
if x isa Array |
|||
grep(x) |
|||
else |
|||
push!(res, x) |
|||
end |
|||
end |
|||
end |
end |
||
grep(arr) |
grep(arr) |
||
res |
|||
end |
end</lang> |
||
⚫ | |||
⚫ | |||
<lang julia>function flat_iterators(arr) |
|||
⚫ | |||
while any(a -> a isa Array, arr) |
|||
<lang julia> |
|||
arr = collect(Iterators.flatten(arr)) |
|||
end |
|||
arr |
|||
⚫ | |||
Benchmarking these three functions using the BenchmarkTools package yields the following results: |
|||
⚫ | |||
arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] |
arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] |
||
@show |
@show flat_mapreduce(arr) |
||
@show |
@show flat_recursion(arr) |
||
@show |
@show flat_iterators(arr) |
||
@btime |
@btime flat_mapreduce($arr) |
||
@btime |
@btime flat_recursion($arr) |
||
@btime |
@btime flat_iterators($arr)</lang>{{out}} |
||
</lang>{{out}} |
|||
<pre> |
<pre> |
||
flat_mapreduce(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8] |
|||
flat_recursion(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8] |
|||
flat_iterators(arr) = [1, 2, 3, 4, 5, 6, 7, 8] |
|||
14.163 μs (131 allocations: 4.27 KiB) |
|||
500.824 ns (4 allocations: 176 bytes) |
|||
28.223 μs (133 allocations: 4.33 KiB) |
|||
</pre> |
</pre> |
||