-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
Cross-posted from mauro3/SimpleTraits.jl#63
This is a feature I'd eventually like to see supported in Julia. I'm not 100% sure where I should post it, so I figured it might be appropriate to post it 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 the BarTrait
. Is this something that could be implemented in a traits package? Or would it need to be implemented in the Julia language itself?
Minimum working example
abstract type MyTrait end
struct FooTrait <: MyTrait end
struct BarTrait <: MyTrait end
struct A end
struct B end
struct C end
struct D end
MyTrait(::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})"
Metadata
Metadata
Assignees
Labels
No labels