Read Online
Download PDF
Additional resources
Revision history
Known typos/bugs
Report a bug
License terms
About the author
"node388_1.gif" "node388_2.gif" "node388_3.gif"   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.

"node388_23.gif" "node388_24.gif" "node388_25.gif"

Created by Wolfram Mathematica 6.0  (05 February 2009) Valid XHTML 1.1!