Parametric type in an variable length Tuple?


#1

I have a problem where I have a struct of parametrically typed functions contained in another struct - to make user selected functions available and type stable. This is fine for one set of functions, but I need N sets of functions! and all type stable. This is the naive approach, which doesn’t work unless all sets of functions are identical:

struct FunctionSet{A,B,C}
  func_a::A
  func_b::B
  func_c::C   
end

struct SomeStruct{N,A,B,C}
   function_sets::NTuple{N,FunctionSet{A,B,C}}
end

Any ideas on how to achieve this for multiple varying FunctionSets? Is this possible?


#2

I don’t think this is what you need, but I post it in case it is:

struct SomeStruct{N,FS<:FunctionSet}
   function_sets::NTuple{N,FS}
end

Otherwise, if your functionsets are different, then it is not a NTuple anymore. But you could do:

struct SomeStruct{T<:Tuple}
   function_sets::T
end

and check in the constructor that the elements of the function_sets are indeed <:FunctionSet.


#3
struct SomeStruct{T<:Tuple{Vararg{<:FunctionSet}}}
    function_sets::T
end

#4

Your right it’s not an NTuple, just some grouping of N sets of different but interchangeable functions that are type stable.


#5

And if you do want to have N available:

struct SomeStruct{N,T<:NTuple{N,FunctionSet}}
           function_sets::T
end
(::Type{SomeStruct})(a::NTuple{N,FunctionSet}) where {N} = SomeStruct{N,typeof(a)}(a)

#6

The first one is perfect, Thanks!


#7

@Raf, can you mark the solution (with the tick)?


#8

Any ideas on how to loop over these using a for loop, maintaining type stability? I keep getting union types.

Recursion works great for this but tends to confuse people…


#9

I’m pretty sure that you need recursion.


#10

You could try https://github.com/cstjean/Unrolled.jl


#11

Ok good to know. Unrolled looks interesting, but would you reccomend it as a dependency for core behaviour in a package?