![]() |
  |
|
4.6.2.3 Using constraints to make functions safer Here is another example: a function extracts a sublist of < n > elements from a list, but only if < n > is not larger than the length of the list :
If, for comparison, we just use Take, we get an error message in the second case :
However, our function is not completely foolproof, since the following call results in an error :
It will be better to restrict our variables as follows :
Sometimes we may need some action to be performed in the case of incorrect input, for example some catchall error message to be issued or the error input analyzed for the error type. In this case, we may use a technique based on a possibility of Mathematica functions to have multiple definitions (to be discussed in the next session in detail). What we have to do is just to give our function another more general definition, like this:
In the last definition we used the pattern with a double underscore (BlankSequence), to account for a case of 2 or more arguments, which is what we need here.
|
|||||||||||||||||