How to do a multi-line array comprehension?

Viewed 390

If I want to create an array with comprehension, but have the logic be multiple lines, how can I do that in Julia?

E.g.

[ ...logic... for x=1:10]

Except the logic is more clearly written in multiple lines with the last line yielding what I want?

2 Answers

Generally, do syntax is preferred for this sort of thing, but note that this can be done in a regular array comprehension, you just have to wrap it in parens and use semicolons for line-breaks:

[(y = x + 1;
  z = y^2 + x;
  z^4 + 2y) for x in 1:5]

results in

5-element Array{Int64,1}:
     629
   14647
  130329
  707291
 2825773

map(iterator) do x does this:

map(1:5) do x
    1+1         # this line is un-yielded logic that precedes the final value 
    x           # this final line is what is returned in the resulting array
end

results in:

5-element Array{Int64,1}:
 1
 2
 3
 4
 5
Related