Skip to content

Function to perform branching automatically to solve inference failures #120

@Tortar

Description

@Tortar

Currently inference fails inferring an abstract type

julia> using LightSumTypes

julia> @sumtype X(Bool, Int, Vector{Bool}, Vector{Int})

julia> xs = [X([1,2]), X(true)]

julia> Base.sum(x::X) = sum(variant(x));

julia> @code_warntype sum.(xs)
MethodInstance for (::var"##dotfunction#230#3")(::Vector{X})
  from (::var"##dotfunction#230#3")(x1) @ Main none:0
Arguments
  #self#::Core.Const(var"##dotfunction#230#3"())
  x1::Vector{X}
Body::AbstractVector
1%1 = Base.broadcasted(Main.sum, x1)::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(sum), Tuple{Vector{X}}}%2 = Base.materialize(%1)::AbstractVector
└──      return %2

but this is not fundamental, we would need a way to forward a function to its variant, without extracting the variant itself, adding something like this in the source code works:

function apply(f::Function, sumt)
   v = $LightSumTypes.unwrap(sumt)
   $(branchs(variants, :(return f(v))))
end

since

julia> Base.sum(x::X) = apply(sum, x);

julia> @code_warntype sum.(xs)
MethodInstance for (::var"##dotfunction#230#1")(::typeof(sum), ::Vector{X})
  from (::var"##dotfunction#230#1")(x1, x2) @ Main none:0
Arguments
  #self#::Core.Const(var"##dotfunction#230#1"())
  x1::Core.Const(sum)
  x2::Vector{X}
Body::Vector{Int64}
1%1 = Base.broadcasted(Main.apply, x1, x2)::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(apply), Tuple{Base.RefValue{typeof(sum)}, Vector{X}}}%2 = Base.materialize(%1)::Vector{Int64}
└──      return %2

only though for functions with a unique sumtype. I think with generated functions we could create an apply(f, args::Tuple) function which works for any mixture of sumtypes and normal types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions