Running Generators as single line version of a for loop


#1

Is there an elegant way to run a Generator? What I want is this:

>@run println(i) for i in 1:3
1
2
3 

By the following definition I can get pretty close:

>macro run(ex)
     :(for x in ($ex); end)
 end

>@run (println(i) for i in 1:3)

Two questions:

  • Is this as efficient as a for loop?
  • Can I get rid of the parens?

#2

You can use collect which will also return an array with all the “yielded” values.

You could also have written it as:

julia> foreach(println, 1:3)
1
2
3

#3

Or really just for i in 1:3 println(i) end


#4

And you must use $(esc(ex)) instead.


#5

Or really just println(1:3...) :slight_smile: (of course that doesn’t insert the newlines, so it isn’t equivalent).
Or println.(1:3);


#6

Ah, that’s the one I was looking for. Thanks!