Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metaprogramming within docstring with @eval

Tags:

julia

I'm attempting to associate a docstring with a function that is defined with an @eval macro; I also wish to use symbols to dynamically generate the docstrings.

for (f, name) in ((:add, :addition), ... )
    @eval begin
        @doc "Documentation for $name" ->
        function f(args)
             ## FUNCTION BODY
        end
    end
end

While I can successfully reference $name from within the @eval statement, I cannot reference $name from within the docstring itself. It gives the error UndefVarError: name not defined.

1) Is there a way to get this to work? I've tried a number of ways to get out of the @doc scope and to gain access to variables in the surrounding scope, but I haven't been successful.

2) What is the nature of the -> syntax?
I got the -> syntax from Github, but I can find no mention of it in the Julia documentation, and even having used Julia for a decent while, I haven't encountered it before.

like image 545
hyperdelia Avatar asked Mar 24 '16 01:03

hyperdelia


2 Answers

As linked to by @jverzani, all that is needed is an additional $. One $ is needed for expression interpolation, and the other is needed for the string interpolation. The final code is as follows:

for (f, name) in ((:add, "addition"), (:sub, "subtraction"), ...)
    @eval begin
        @doc """
        This is the function $($name)
        """
        function $f()
            ## FUNCTION BODY
        end
    end
end

Super simple once you know the answer...

like image 186
hyperdelia Avatar answered Sep 18 '22 04:09

hyperdelia


As @scls noted this needs to be slightly modified for Julia 0.5. From the Advanced Usage section of the docs the above example should now look something like

for (f,n) in ((:foo, "foo"), (:bar, "bar"))
    @eval begin
                @doc "This is the function $($n)" $f
        function $f()
            println($n)
        end
    end
end

```

like image 40
Colm Ryan Avatar answered Sep 20 '22 04:09

Colm Ryan