Reputation: 319
I have a function that returns different functions depending on the value of an integer i
. Some values of this integer return the same function but I am unsure how to implement this. The function was formerly:
function myfunc(x,i::Int)
if i == i_A
return funcA(x)
elseif i == i_B
return funcB(x)
elseif i == i_C
return funcB(x)
elseif i == i_D
return funcB(x)
else
throw(DomainError(i, "Error"))
end
which I have unsuccessfully tried to abbreviate to:
function myfunc(x,i::Int)
if i == i_A
return funcA(x)
elseif i == i_B || i_C || i_D
return funcB(x)
else
throw(DomainError(i, "Error"))
end
What is the proper syntax for multiple 'or' in a julia if loop?
Upvotes: 1
Views: 68
Reputation: 432
As stated in the comments, you can use:
function myfunc(x,i::Int)
if i == i_A
return funcA(x)
elseif i == i_B || i == i_C || i == i_D
return funcB(x)
else
throw(DomainError(i, "Error"))
end
end
Or you can use the keyword in
like this:
function myfunc(x,i::Int)
if i == i_A
return funcA(x)
elseif i in [i_B, i_C, i_D]
return funcB(x)
else
throw(DomainError(i, "Error"))
end
end
I personnaly prefer the latter because it is easier to read, and easier to edit.
You can even change your test dynamically by making the array [i_B, i_C, i_D]
a variable and change its content dynamically.
Upvotes: 2