Multiple dispatch on multiple parametric types

In Julia, can I achieve the behavior:

f(a::String, b::Int) = false
f(b::Int, a::String) = false
f(a::Int, b::Int) = a+b
f(a::String, b::String) = "woohoo!"

Using parametric types for the first two functions? Something like:

f(a::T, b::S) where {T!=S} = false

Or something like this.

Upvotes: 1

Views: 427

Answers (2)

tholy
tholy

Reputation: 12179

The "computations" you're allowed to do on the types in a where statement are very limited. Basically just subtyping, e.g., T<:AbstractFloat. You can look into @generated functions if you need more sophisticated type computations, but beware some people go crazy and use them where other techniques would be better. There are compile-time and code-size advantages to writing code in a way that the compiler can reason about, for example in the answer from user2891936.

Upvotes: 1

dberge
dberge

Reputation: 331

I think this is what you are looking for. Julia will always dispatch to the least ambiguous method.

f(a::T,b::S) where {T,S} = T==S
f(a::T,b::T) where {T<:Number} = a+b
f(a::T,b::T) where {T<:String} = "woohoo!"

Upvotes: 4

Related Questions