How to reference the type of a function in a struct?



This is the type I want to use:

struct S 

However I want to allow only functions F which are of exactly this type:

 F(n::Int, k::Int)::BigInt

How can I express this in the struct S?


You cannot. Julia does not encode the arguments and return-type of functions (or more like “methods”) in their type.

Side note, if you care about performance, then you should parameterize on the function-type:

struct S{T<:Function}


There is FunctionWrappers.jl.


You cannot express it in the struct directly, but you can enforce something like this in the constructor, by checking the output of Base.return_types(F, (Int, Int)).


This is not really a good idea. You are tying the logic of your code to inference (which is a heuristic) and the result will be very brittle.


Is it the implementation that makes it brittle, or is the goal of restricting the input/output types of F inherently problematic?


Something like (updated thanks @Tamas_Papp)

struct S 
    S(F::Function, n::Int) = new( (n::Int, k::Int) -> F(n, k)::BigInt, n)

might be ok?

But any attempt to try to error when the struct S is created (as opposed to when S.F is used) seems difficult.


Since the closure isa Function, I guess you need some extra step not to get an infinite loop.


Thanks, updated.


Would in this case still be advantageous to parametrize the sctruc with the function-type as proposed by @mauro3 ?


Likely, yes.


Thank you!