Running Generators as single line version of a for loop

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?

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
1 Like

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

1 Like

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

1 Like

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);

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