Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dispatch on arrays where all elements in the array have a certain trait #2

Open
DilumAluthge opened this issue Jul 26, 2019 · 0 comments

Comments

@DilumAluthge
Copy link

Cross-posted from JuliaLang/julia#5 (comment), andyferris/Traitor.jl#9, and mauro3/SimpleTraits.jl#63.

@HarrisonGrodin The traits write-up is great!

In your vision of traits, would it be possible to dispatch on arrays where all elements in the array have a certain trait?

Here's a minimum working example. All of the lines currently work in Julia except for the last line:

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})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant