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
<lang julia>using BenchmarkTools▼
The following version of flatten makes use of the higher order function ''mapreduce''.
<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
function grep(v)
if x isa Array
grep(x)
else
push!(res, x)
end
end
end
grep(arr)
end</lang>
</lang>▼
<lang julia>function flat_iterators(arr)
▲Using the Julia standard Iterators library:
while any(a -> a isa Array, 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
@show
@show
@btime
@btime
@btime
<pre>
</pre>
|