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 auto-flattened nested arrays. The following version of flatten makes use of the higher order function ''mapreduce''.
(Note that Julia versions prior to 0.5 automatically flattened nested arrays.)
<lang julia>using BenchmarkTools


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
</lang>

function flat_mapreduce(arr)
mapreduce(vcat, arr, init=[]) do x
isflat(x) ? x : flat(x)
end
end</lang>
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 flat1(arr)
<lang julia>function flat_recursion(arr)
rst = Any[]
res = []
grep(v) = for x in v
function grep(v)
if isa(x, Array) grep(x) else push!(rst, x) end
for x in v
if x isa Array
grep(x)
else
push!(res, x)
end
end
end
end
grep(arr)
grep(arr)
rst
res
end
end</lang>
Using the Iterators library from the Julia base:
</lang>
<lang julia>function flat_iterators(arr)
Using the Julia standard Iterators library:
while any(a -> a isa Array, arr)
<lang julia>
flat2(arr) = (while any(a -> a isa Vector, arr) arr = collect(Iterators.flatten(arr)) end; arr)
arr = collect(Iterators.flatten(arr))
end
arr
end</lang>
Benchmarking these three functions using the BenchmarkTools package yields the following results:
<lang julia>using BenchmarkTools


arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]


@show flat(arr)
@show flat_mapreduce(arr)
@show flat1(arr)
@show flat_recursion(arr)
@show flat2(arr)
@show flat_iterators(arr)


@btime flat(arr)
@btime flat_mapreduce($arr)
@btime flat1(arr)
@btime flat_recursion($arr)
@btime flat2(arr)
@btime flat_iterators($arr)</lang>{{out}}
</lang>{{out}}
<pre>
<pre>
flat(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat_mapreduce(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat1(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat_recursion(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat2(arr) = [1, 2, 3, 4, 5, 6, 7, 8]
flat_iterators(arr) = [1, 2, 3, 4, 5, 6, 7, 8]
17.200 μs (193 allocations: 9.44 KiB)
14.163 μs (131 allocations: 4.27 KiB)
504.145 ns (5 allocations: 256 bytes)
500.824 ns (4 allocations: 176 bytes)
36.699 μs (106 allocations: 3.73 KiB)
28.223 μs (133 allocations: 4.33 KiB)
</pre>
</pre>