Defining a conditional method in Julia

#1

Hello,

We can define methods on functions that depend on types of arguments. But can we define methods that depend on some conditionals of arguments. To make myself clear the following syntax is not permitted:

function foo(x::dims(x)==2)
    println("2")
end

function foo(x::dims(x)==3)
    println("3")
end

We could circumvent this problem by say:

function foo(x)
    if dims(x) == 2
        foo2(x)
    elseif dims(x) == 3
        foo3(x)
    end
end

foo2(x) = println("2") 
foo3(x) = println("3")

Is there any other way (a more concise or elegant way) of dealing with this?

Thanks.

#2

You can use traits, or more generally convert the information that you condition on to a type. Eg

_dims(x) = Val{dims(x)}()
foo(x) = _foo(_dims(x), x)
_foo(::Val{2}, x) = println("2")
_foo(::Val{3}, x) = println("3")

This involves dynamic dispatch (except when the compiler gets clever and manages to fold the constants), so it will not help you make things faster. But it can provide an extensible alternative to a bunch of ifs.

3 Likes
#3

Thanks for your help!