I am writing down a set of functions, and I want to make sure that some of the arguments are bounded within some given values.
For the sake of simplicity, say that I only have the following function:
w is bounded between
1.0. Right now, I am throwing an error if
w is lower than
0.0 or larger than
if w < 0 || w > 1
error("0 ≤ w ≤ 1");
I was wondering whether there are more efficient ways to approach this problem. I was thinking that since
w is a restricted
Float64 I could define a type that takes into account its bounds. However, I am not sure whether this is good practise, and if it can be easily done in Julia.
What would you recommend to do? In my application, I have many arguments to check and individual
if-end are not very tidy.
You could make a custom type, but that seems complicated. How about putting your error check into a function? It would be tidier.
if x < 0 || x > 1
error("0 ≤ x ≤ 1")
function my_fun(w1, w2, w3)
is01(w1); is01(w2); is01(w3);
At the end of the day, you won’t get anything more efficient then what you already have here. It also won’t make any difference in the writability for this isolated case so you need to decide what is the more complete case. What kind of problem are you trying to solve.
Do you have any need to statically dispatch based on the range of the value? (I.e. the range of the values could be determined at compile time.) If not (most likely the case), you are much better off with check on the value at runtime with branches.
If you just want a shorter syntax, just define a function for that check like what you will do in any other language. Type is not the solution to all problems.