Search code examples
functionmethodsconditional-statementsjuliawolfram-mathematica

Condition on arguments of a function in Julia


It is possible to specify the argument type for a function in Julia like : addition(x::Int64,y::Int64). I can, simultaneously, define another function with the same name : addition(x::Float64,y::Int64)

Is it possible to also specify the above function such that instead of a restriction on type, I specify a restriction on the values x or y can take? So, for example, I could say that if x takes values between 1.0 and 15.0 then use one definition of addition and if it take values above 15.0 then use another definition.

So basically I would like to specify the range of values that the arguments of a function can take, like in Mathematica one can do : addition[i_, j_] /; 0.0 <= i <= 15.0 && 0.0 <= j <= 15.0 := i + j.

Thanks!


Solution

  • There is nothing special about what Mathematica does here, every programming language in history can do this, and Julia too.

    addition[i_, j_] /; 0.0 <= i <= 15.0 && 0.0 <= j <= 15.0 := i + j
    

    becomes

    addition(i, j) = (0<=i<=15) && (0<=i<=15) && return i+j
    

    But what should the function do if the inputs do not fall within the ranges? Right now it will return nothing.