tk3369 / BinaryTraits.jl

Can do or not? It's easy. See https://tk3369.github.io/BinaryTraits.jl/dev/
MIT License
51 stars 3 forks source link

Easy syntax for holy trait dispatch function #2

Closed tk3369 closed 4 years ago

tk3369 commented 4 years ago

It seems to be a hassle to define the "entrypoint" function for every function that supports traits.
For example:

function plot(device::T, x::Vector{Float64}, y::Vector{Float64}; color = :black, linewidth = 1) where T
    plot(trait(Plottable,T), device, x, y; color, linewidth)
end

It would be nice to have syntax like:

@holy Plottable plot(device, x::Vector{Float64}, y::Vector{Float64}; color = :black, linewidth = 1)

Note: I can't think of a good verb yet (hence @holy 😄 ).

Tokazama commented 4 years ago

It would be nice if there was some way to write trait based dispatch so it was just like type dispatch. Something like

@function plot(device::T, x::Vector{Float64}, y::Vector{Float64}; color = :black, linewidth = 1) where T<:TraitContract begin
    ...
end
tk3369 commented 4 years ago

Mmm... I don't quite follow the suggestion. It sounds like that you want to bundle the dispatching function and the implementation?

But, there are two possibilities - positive and negative-side of the the trait. In this example, we could implement two plot functions, one with Is{Plottable} and another with Not{Plottable}.

tk3369 commented 4 years ago

Hi @Tokazama,

More holistically, this is the original proposal, which simplifies the holy traits dispatch function. The user still needs to define the function with its first argument being the trait type:

@holy Plottable plot(device, x::Vector{Float64}, y::Vector{Float64}; color = :black, linewidth = 1)

function plot(::Is{Plottable}, device::T, x::Vector{Float64}, y::Vector{Float64}; color = :black, linewidth = 1) where T
    ...
end

Are you asking to combine them into a single definition?

@holy function plot(device::Is{Plottable}, x::Vector{Float64}, y::Vector{Float64}; color = :black, linewidth = 1) 
    ....
end

If so, I like it! :-)

Tokazama commented 4 years ago

Yes! That's exactly what i want. Thank you for reading my mind despite me forgetting about this issue.

The reason I like this approach so much is that it allows the use of a trait in the place of a type. I think that this combined with the really convenient @trait macro would be very helpful in creating succinct meaningful code.