Search code examples
arraysjulialist-comprehension

How to do a multi-line array comprehension?


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?


Solution

  • 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