Nested list comprehensions in Julia
julia
Solution
List comprehensions work a bit differently in Julia:
> [(x,y) for x=1:2, y=3:4]
2x2 Array{(Int64,Int64),2}:
(1,3) (1,4)
(2,3) (2,4)
If `a=[[1 2],[3 4],[5 6]]` was a multidimensional array, `vec` would flatten it:
> vec(a)
6-element Array{Int64,1}:
1
2
3
4
5
6
Since a contains tuples, this is a bit more complicated in Julia. This works, but likely isn't the best way to handle it:
function flatten(x, y)
state = start(x)
if state==false
push!(y, x)
else
while !done(x, state)
(item, state) = next(x, state)
flatten(item, y)
end
end
y
end
flatten(x)=flatten(x,Array(Any, 0))
Then, we can run:
> flatten([(1,2),(3,4)])
4-element Array{Any,1}:
1
2
3
4
Problem
In python I can do nested list comprehensions, for instance I can flatten the following array thus: ``` a = [[1,2,3],[4,5,6]] [i for arr in a for i in arr] ``` to get `[1,2,3,4,5,6]` If I try this syntax in Julia I get: ``` julia> a ([1,2,3],[4,5,6],[7,8,9]) julia> [i for arr in a for i in arr] ERROR: syntax: expected ] ``` Are nested list comprehensions in Julia possible?