Thanks --- so in this particular case I can work around it. But is that true that in general, I cannot write a macro with a syntax
@mymacro body... end that would get the AST of body...? Ie if the language did not have `for` or `while`, or any of the constructs which make blocks, I could not reimplement them with a macro. Best, Tamas On Sun, May 03 2015, Jameson Nash <[email protected]> wrote: > You can do this with a functional form: > > function with_output_to_string(f) > f(IOBuffer()) > end > > with_output_to_string() do io > println(io, "testing") > @printf(io, "pi is %.5f", Float64(pi)) > end > > see also: https://github.com/JuliaLang/julia/issues/7022 > > On Sun, May 3, 2015 at 6:18 AM Tamas Papp <[email protected]> wrote: > >> Hi, >> >> I am trying to write something analogous to >> COMMON-LISP:WITH-OUTPUT-TO-STRING, what I have so far is >> >> macro with_output_to_string(stream, expr) >> quote >> let $(esc(stream)) = IOBuffer() >> $expr >> takebuf_string($(esc(stream))) >> end >> end >> end >> >> Works fine: >> >> @with_output_to_string io begin >> println(io, "testing") >> @printf(io, "pi is %.5f", Float64(pi)) >> end >> >> but I have a couple of questions: >> >> 1. Is there a way I can get rid of the `begin`? Julia syntax for >> built-ins that have implicit blocks (`for`, `function`) has no `begin`, >> is it possible to write a macro in a similar style? Ie is there >> something analogous to COMMON-LISP:&BODY in Julia? (in effect, not in >> syntax, I know about varargs, but they don't look right here). >> >> 2. I thought that if I make the first argument STDOUT, I can get rid of >> the stream name in the body, but it doesn't work (still prints to >> console). What is the right way? >> >> 3. In Common Lisp, it is common for the first argument to be an >> s-expression that is then destructured. Is that idiomatic in Julia? Can >> you point me to some examples? >> >> Best, >> >> Tamas >>
