How to assign a particular method for a function with the exact type signature to an lvalue?

I’d like to be able to set an lvalue to a particular method. Essentially use it as a function pointer so that it can be called later in some other code. I’d like to set the method rather than the function because I’m worried about type stability for the return type. A simple example of assigning the function is provided below, but I would like to assign a particular method.

abc(x::Int) = return 2.0
abc(x::Float32) = return 2

def = abc

Not sure if it is a good way to ensure type stability… but you could use invoke, e.g.
def(x::Int) = invoke(ABC, Tuple{Int}, x).

you probably don’t need to do this.

1 Like

Take a look at FunctionWrappers.jl

Base julia does not have syntax for this, because dispatching to a method given a function name and arguments is a central pillar of its design. What problem are you trying solve?


The question/problem seems perfectly clear:

GitHub - yuyichao/FunctionWrappers.jl was made for this use case.

As an example:

using FunctionWrappers: FunctionWrapper

abc(x::Int) = 1.0
abc(x::Float32) = 2

abc_wrap = convert(FunctionWrapper{Int, Tuple{Float32}}, abc)
abc_wrap(5.0f0) # returns 2 and is type stable

Basically, this can precompute the lookup that the dynamic dispatch would typically do at runtime. This can be useful if you want to e.g. have an array of function (pointers) and select them by index where all functions have the same signature + return value.

Note, that this does make you vulnerable to #265:

julia> abc(x::Float32) = 5; # redefine function

julia> abc(5.0f0)

julia> abc_wrap(5.0f0)