How to dispatch according to the number I put in the type parameter?

struct MM{N}
end

f(x::MM{N}) where N>5 = println("GREATER THAN 5")
f(x::MM{N}) where N<3 = println("LESS THAN 3")

f(MM{2}())

I want to dispatch according to the number I put in the type parameter. Is there a way to do this?

Thanks

f(::Val{3}) = println("is 3")
f(::Val{5}) = println("is 5")
g(x::Int) = f(Val(x))

and then:

julia> g(3)
is 3

julia> g(5)
is 5

But please read this first:
https://docs.julialang.org/en/v1/manual/performance-tips/#Types-with-values-as-parameters-1

You can use traits (my example is with just one branch):

struct MM{N} end
_trait(::MM{N}) where {N} = Val{N ≤ 3}()
f(x::MM) = _f(_trait(x))
_f(::Val{true}) = println("≤ 3")
_f(::Val{false}) = println("> 3")

(ps: please use more informative topic names)

5 Likes

However this is not something I want, if you look at the where statement, you can see that MM{6},MM{7} will dispatch to the first one. I want to create ranges …

Value based dispatch…
I like it.
Thanks

Note that for simple logic like this, the compiler is smart enough to eliminate unused branches, so you can just write:

function f(::MM{N}) where N
    if N > 5
        return println("GREATER THAN 5")
    elseif N < 3
        return println("LESS THAN 3")
    end
end

and it will be just as efficient as the other proposed solutions. For more complex cases, you have be a bit careful, that you’re not calling functions with side effects in your logic, otherwise the compiler won’t be able to specialize on N and there will be some overhead.

3 Likes