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

`@sum_type` doesn't work with constrained type parameter in variant

Open Tortar opened this issue 1 year ago • 6 comments

e.g. this

julia> using SumTypes

julia> @sum_type A{X<:Union{Real, SumTypes.Uninit}} begin
           B{X<:Union{Int, SumTypes.Uninit}}(a::X)
           C{X}(b::X)
       end

throws

ERROR: LoadError: constructor parameters (Any[:(X <: Union{Int, SumTypes.Uninit})]) for B, not a subset of sum type parameters [:X]
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:35
 [2] generate_constructor_data(T_name::Symbol, T_params::Vector{Symbol}, T_params_constrained::Vector{Any}, T_nameparam::Expr, hide_variants::Bool, blk::Expr)
   @ SumTypes ~/.julia/dev/SumTypes/src/sum_type.jl:75
 [3] _sum_type(T::Expr, hidden::QuoteNode, blk::Expr)
   @ SumTypes ~/.julia/dev/SumTypes/src/sum_type.jl:31
 [4] _sum_type(T::Expr, blk::Expr)
   @ SumTypes ~/.julia/dev/SumTypes/src/sum_type.jl:6
 [5] var"@sum_type"(__source__::LineNumberNode, __module__::Module, T::Any, args::Vararg{Any})
   @ SumTypes ~/.julia/dev/SumTypes/src/sum_type.jl:3
in expression starting at REPL[6]:1

but I think this could work

Tortar avatar Feb 10 '24 00:02 Tortar

inspecting the test I understood I should use Union{Real, Uninit}, this feels a bit awkward but probably then this can be closed

Tortar avatar Feb 10 '24 01:02 Tortar

ok I actually changed slightly the issue, this is now something which could be probably improved

Tortar avatar Feb 10 '24 01:02 Tortar

Yeah, this'll require a bit of thought to design correctly but should be possible I think. I wonder if we should just insert the Union{..., Uninit} ourselves if people constrain the parameters?

MasonProtter avatar Feb 13 '24 19:02 MasonProtter

In my opinion yes, I'm already doing this in MixedStrucTypes.jl, there shouldn't be any problem doing that if I'm not mistaken

Tortar avatar Feb 13 '24 21:02 Tortar

I must say though, I'm a little skeptical of the idea of there being instances of type A for which B is not constructable. Like, is there usecases where that's desirable?

MasonProtter avatar Feb 13 '24 23:02 MasonProtter

I'm not sure, but maybe it can be considered analogous to the case where you have a Union of types, there you can constrain parameters differently if you want

Tortar avatar Feb 15 '24 12:02 Tortar

I ended up having ambiguity problems in MixedStructTypes because of this issue so I fixed it :-)

Tortar avatar May 20 '24 15:05 Tortar