Skip to content
New issue

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

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

Already on GitHub? # to your account

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

Closed
DilumAluthge opened this issue Jul 16, 2019 · 2 comments
Closed

Comments

@DilumAluthge
Copy link

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 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})"
@mauro3
Copy link
Owner

mauro3 commented Jul 16, 2019

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.

@DilumAluthge
Copy link
Author

Thanks for such a quick answer! It sounds like fast-dispatch on the traits of array elements might need to be implemented in Julia itself.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants