user3120868
user3120868

Reputation: 93

Is it possible to do multiple dispatch on NOT-a-type?

To simplify, I am trying to write a function with two arguments, where:

  1. The base method accepts two Integers as arguments

    func(x::Int, y::Int) = something

  2. Additional methods accept either or both arguments as arbitrary types, map these arguments onto integers, and call the base method

  3. Additional methods accept either or both arguments as arrays (or ::Colon types) and generate an array from applying the appropriate prior methods (1) or (2) elementwise.

Unsurprisingly (in hindsight), this approach generates method ambiguities. Given the types of arguments provide to a function, Julia chooses a valid method with the most specific types. But if x is an array and y is an Int, the following methods are equally specific and Julia doesn't know which one to call:

I would like to do something like

Is there such as thing as a not-a-type type? Am I thinking about this the wrong way? Is there a canonical way to approach this sort of problem?

For context, I am trying to implement a Base.getindex for a struct I wrote, and I want the getindex to support many different ways to index the struct when the contents of the struct could be somewhat diverse. Under-the-hood, elements in the struct are indexed by integers, but the user might be using almost-arbitrary non-integer types to index elements in the struct (I don't want to force the user to use particular types to index elements).

Upvotes: 5

Views: 347

Answers (1)

Bill
Bill

Reputation: 6086

You can specify the (Array, Int) case and then add less specific methods:

julia> func(x::Array, i::Int) = 0
func (generic function with 1 method)

julia> func(x, i::Int) = 1
func (generic function with 2 methods)

julia> func(x::Array, i) = 2
func (generic function with 3 methods)

julia> methods(func)
# 3 methods for generic function "func":
[1] func(x::Array, i::Int64) in Main at REPL[1]:1
[2] func(x, i::Int64) in Main at REPL[2]:1
[3] func(x::Array, i) in Main at REPL[3]:1

Upvotes: 4

Related Questions