Generic dispatch with Symbols

荒凉一梦 提交于 2019-12-09 06:40:12

问题


I was wondering if there was a way to use Symbols for multiple dispatch, but also include a "catch-all method". i.e. something like

function dispatchtest{alg<:Symbol}(T::Type{Val{alg}})
  println("This is the generic dispatch. The algorithm is $alg")
end
function dispatchtest(T::Type{Val{:Euler}})
  println("This is for the Euler algorithm!")
end

The second one works and matches what's in the manual, I'm just wondering how you get the first one to work.


回答1:


You can do it this way:

julia> function dispatchtest{alg}(::Type{Val{alg}})
           println("This is the generic dispatch. The algorithm is $alg")
       end
dispatchtest (generic function with 1 method)

julia> dispatchtest(alg::Symbol) = dispatchtest(Val{alg})
dispatchtest (generic function with 2 methods)

julia> function dispatchtest(::Type{Val{:Euler}})
           println("This is for the Euler algorithm!")
       end
dispatchtest (generic function with 3 methods)

julia> dispatchtest(:Foo)
This is the generic dispatch. The algorithm is Foo

julia> dispatchtest(:Euler)
This is for the Euler algorithm!


来源:https://stackoverflow.com/questions/39314925/generic-dispatch-with-symbols

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!