function memoize(f, t) cache = dict{any, t}() function g(args...)::t key = make_key(args...) get!(cache, key) f(args...) end end g end fib = memoize(x::int -> begin if x == 2 return 2 end if x == 1 return 1 end fib(x - 1) + fib(x - 2) end, int)
this get, sadly doesn't recognise return type though annotated.
also, there way annotate return type of anonymous function?
@code_warntype fib(3) variables: #self#::#g#40{##44#45,datatype,dict{any,int64}} args::tuple{int64} key::tuple{int64} #39::##39#41{tuple{int64},##44#45} body: begin ssavalue(0) = (core.getfield)(#self#::#g#40{##44#45,datatype,dict{any,int64}},:t)::datatype key::tuple{int64} = (core.tuple)((core.getfield)(args::tuple{int64},1)::int64)::tuple{int64} # line 20: #39::##39#41{tuple{int64},##44#45} = $(expr(:new, ##39#41{tuple{int64},##44#45}, :(args), :((core.getfield)(#self#,:f)::##44#45))) ssavalue(1) = #39::##39#41{tuple{int64},##44#45} ssavalue(2) = (core.getfield)(#self#::#g#40{##44#45,datatype,dict{any,int64}},:cache)::dict{any,int64} return (core.typeassert)((base.convert)(ssavalue(0),$(expr(:invoke, lambdainfo get!(::##39#41{tuple{int64},##44#45}, ::dict{any,int64}, ::tuple{int64}), :(main.get!), ssavalue(1), ssavalue(2), :(key))))::any,ssavalue(0))::any end::any
update
i made package provides basic support type inference friendly generic function memoization via macro. allows customize cache key function arguments.
in order julia specialize implementation specific datatype
, must use ::type{t}
parametric type:
function memoize{t}(f, ::type{t}) …
that simple change means julia specialize methods each , every type memoize
encounters, instead of making 1 specialization datatype
s.
Comments
Post a Comment