SumTypes.jl icon indicating copy to clipboard operation
SumTypes.jl copied to clipboard

A `compactify_interface` feature that takes a list of types and a list of functions that have methods for these types and "compactifies" them

Open Krastanov opened this issue 2 years ago • 0 comments

As seen in discussions on slack and discourse:

I want to be able to do:

for g in list_of_different_types_of_gates:
    apply!(state, g)
end

without dynamic dispatch or allocations.

apply! is a function that has a ton of non-allocating fast methods of the form apply!(::State, ::OneOfManyDifferentTypes)::State

I have the following approach:

I made a function that takes

  • a list of types
  • a list of functions that have methods defined for these types

and it creates

  • one single sumtype
  • for all the given functions, it defines a method for the new sumtype In pseudo code it looks like
make_sumtype_infrastructure(my_many_types, [:fun1, :fun2]) |> eval
which generates the following code
@sum_type MySumType
    OneOfMyOriginalTypes(...)
    ...
end
function fun1(arg::MySumType)
    @case arg begin
        OneOfMyOriginalTypes(...) => fun1(OneOfMyOriginalTypes(...))
        ...
    end
end

The implementation is at https://github.com/QuantumSavory/QuantumClifford.jl/pull/119/commits/17cc1ca6bfcef00356ec3160d73a644df1f85235

It is based on a discussion from https://discourse.julialang.org/t/ann-sumtypes-jl-v0-4/97038/4?u=krastanov

Having some reliable form of this officially supported by the library would be amazing (I suspect what I have written is very prone to breaking, as I am not experienced with meta-programing). Especially if it has some way for expanding the sumtype without a ton of invalidations and recompilation (maybe by "padding" the sumtype so that it can be extended) -- that way we can still keep some of the amazing interoperability of julia packages.

Krastanov avatar May 17 '23 03:05 Krastanov