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

question

#1

This is the type I want to use:

struct S 
    F::Function
    n::Int
end

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?


#2

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}
    F::T
    n::Int
end

#3

There is FunctionWrappers.jl.


#4

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)).


#5

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.


#6

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


#7

Something like (updated thanks @Tamas_Papp)

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

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.


#8

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


#9

Thanks, updated.


#10

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


#11

Likely, yes.


#12

Thank you!