Flatten a list: Difference between revisions

→‎{{header|Julia}}: Interpolate variable from global scope, as required for accurate benchmarking; more idiomatic style
(Flatten a list in XBasic)
(→‎{{header|Julia}}: Interpolate variable from global scope, as required for accurate benchmarking; more idiomatic style)
Line 2,226:
 
=={{header|Julia}}==
(Note that Julia versions prior to 0.5 auto-automatically flattened nested arrays. The following version of flatten makes use of the higher order function ''mapreduce''.)
<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:
<lang julia>function flat1flat_recursion(arr)
rstres = Any[]
function grep(v) = for x in v
iffor isa(x, Array)in grep(x) else push!(rst, x) endv
if x isa Array
grep(x)
else
push!(res, x)
end
end
end
grep(arr)
rstres
end</lang>
Using the Julia standard 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)
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, []]
 
@show flatflat_mapreduce(arr)
@show flat1flat_recursion(arr)
@show flat2flat_iterators(arr)
 
@btime flatflat_mapreduce($arr)
@btime flat1flat_recursion($arr)
@btime flat2flat_iterators($arr)</lang>{{out}}
</lang>{{out}}
<pre>
flatflat_mapreduce(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat1flat_recursion(arr) = Any[1, 2, 3, 4, 5, 6, 7, 8]
flat2flat_iterators(arr) = [1, 2, 3, 4, 5, 6, 7, 8]
1714.200163 μs (193131 allocations: 94.4427 KiB)
504500.145824 ns (54 allocations: 256176 bytes)
3628.699223 μs (106133 allocations: 34.7333 KiB)
</pre>
 
1

edit