You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an array, I'd like to dispatch to one method if all elements in the array have the FooTrait, and to a different method if all elements in the array have the BarTrait. Is this possible in SimpleTraits.jl?
Minimum working example
abstract type MyTrait endstruct FooTrait <:MyTraitendstruct BarTrait <:MyTraitendstruct A endstruct B endstruct C endstruct D endMyTrait(::Type{A}) =FooTrait()
MyTrait(::Type{B}) =FooTrait()
MyTrait(::Type{C}) =BarTrait()
MyTrait(::Type{D}) =BarTrait()
f(x::T) where T =_f(MyTrait(T), x)
_f(::FooTrait, x) ="foo"_f(::BarTrait, x) ="bar"_f(::FooTrait, x::AbstractArray) ="foo array"_f(::BarTrait, x::AbstractArray) ="bar array"f(A()) # "foo"f(B()) # "foo"f(C()) # "bar"f(D()) # "bar"MyTrait(::Type{<:AbstractArray{T, N}}) where T where N =MyTrait(T)
f([A(), A()]) # "foo array"f([B(), B()]) # "foo array"f([C(), C()]) # "bar array"f([D(), D()]) # "bar array"f([A(), B()]) # I want this to return "foo array", but instead it throws "ERROR: MethodError: no method matching MyTrait(::Type{Any})"
The text was updated successfully, but these errors were encountered:
I don't think you can do f([A(), B()]) in general if you need fast dispatch as the array type cannot encode this. You'd have to loop over all elements and check them individually and for this you'd need to call the trait-function with the instance and not the type.
SimpleTraits cannot help with this.
I'll close this but feel free to keep asking questions here.
Given an array, I'd like to dispatch to one method if all elements in the array have the
FooTrait
, and to a different method if all elements in the array have theBarTrait
. Is this possible in SimpleTraits.jl?Minimum working example
The text was updated successfully, but these errors were encountered: