Question about method dispatch with composite types

In the bellow script, being dc.x and dc.y equal to 1 the default, how may I (if possible) create the following methods:

divide(a,Clock()) and divide(a,Pendulum())

returning the same as divide(a,CLock(1)), divide(a,Pendulum(1)), respectively.

abstract type Wave end

struct Clock <: Wave
      x::Int
end

struct Pendulum <: Wave
    y::Int
end

function divide(a, dc::Clock)
    if dc.x == 1
        return a/2
    else
        return a/10
    end
end

function divide(a, dc::Pendulum)
    if dc.y == 1
        return a/20
    else
        return a/100
    end
end

If I understand your question, you could add

Clock() = Clock(1)
Pendulum() = Pendulum(1)

then

a = 100
divide(a, Clock(1)) == divide(a, Clock()) == 50.0
divide(a, Pendulum(1)) == divide(a, Pendulum()) == 5.0

However, what you are after is likely available more elegantly too.
Are you looking for something like this?

abstract type Wave end

struct Clock <: Wave
      slow::Bool
end

struct Pendulum <: Wave
    slow::Bool
end

function divide(a, wave::Clock)
    return wave.slow ? a/2 : a/10
end

function divide(a, wave::Pendulum)
    return wave.slow ? a/20 : a/100
end

const SlowClock = Clock(true)
const FastClock = Clock(false)
const SlowPendulum = Pendulum(true)
const FastPendulum = Pendulum(false)

then

julia> a = 100
100

julia> divide(a, SlowClock)
50.0

julia> divide(a, FastClock)
10.0

julia> divide(a, SlowPendulum)
5.0

julia> divide(a, FastPendulum)
1.0

Thank you very much. Your suggestion worked like a charm!

1 Like