hyperdelia
hyperdelia

Reputation: 1145

Metaprogramming within docstring with @eval

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.

Upvotes: 5

Views: 437

Answers (2)

Colm Ryan
Colm Ryan

Reputation: 71

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

```

Upvotes: 4

hyperdelia
hyperdelia

Reputation: 1145

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...

Upvotes: 8

Related Questions