Understanding memoization.jl

Chong_Wang
Tue, 15 Aug 2017 19:14:54 +0000
General Usage

I am trying to understand memoization.jl by simonster to obtain a good understanding of macros. First I tried to macroexpand the output:

julia> using Memoize

julia> macroexpand(:(@memoize function x(a) a end))
quote  # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 107:
    function ##x_unmemoized(a) # REPL[3], line 1:
        a
    end # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 108:
    empty!(ObjectIdDict()) # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 109:
    x(a)::Any = begin  # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 109:
            if haskey(ObjectIdDict(), (a,))
                (ObjectIdDict())[(a,)]::Core.Inference.return_type(##x_unmemoized, typeof((a,)))
            else
                (ObjectIdDict())[(a,)] = ##x_unmemoized(a)
            end
        end
end

It is really weird. I think ##x_unmemoized is intended to be a function but since it starts with #, it should be a comment. Then I tried to evaluate it:

julia> eval(macroexpand(:(@memoize function x(a) a end)))
x (generic function with 1 method)

Everything seems to be fine. However, if I copy the output of macroexpand:

julia> quote  # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 107:
           function ##x_unmemoized(a) # REPL[3], line 1:
               a
           end # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 108:
           empty!(ObjectIdDict()) # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 109:
           x(a)::Any = begin  # /home/wangc/.julia/v0.6/Memoize/src/Memoize.jl, line 109:
                   if haskey(ObjectIdDict(), (a,))
                       (ObjectIdDict())[(a,)]::Core.Inference.return_type(##x_unmemoized, typeof((a,)))
                   else
                       (ObjectIdDict())[(a,)] = ##x_unmemoized(a)
                   end
               end
       end

ERROR: syntax: unexpected else
Stacktrace:
 [1] macro expansion at ./REPL.jl:97 [inlined]
 [2] (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:73

I am totally confused about what is happening here. Anyone give me a hint?

6 posts - 4 participants