"logo.gif"  
Main
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"

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 :

"node388_4.gif"

"node388_5.gif"

"node388_6.gif"

If, for comparison, we just use Take, we get an error message in the second case :

"node388_7.gif"

"node388_8.gif"

"node388_9.gif"

However, our function is not completely foolproof, since the following call results in an error :

"node388_10.gif"

"node388_11.gif"

"node388_12.gif"

It will be better to restrict our variables as follows :

"node388_13.gif"

"node388_14.gif"

"node388_15.gif"

"node388_16.gif"

"node388_17.gif"

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:

"node388_18.gif"

"node388_19.gif"

"node388_20.gif"

"node388_21.gif"

"node388_22.gif"

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!