How to | Balance Brackets and Braces
| All bracketing characters in Mathematica must be balanced. That is, every type of opening bracket must be balanced by a corresponding closing bracket. If there is an imbalance, then Mathematica will not evaluate the cell. The Mathematica front end contains several convenient tools that let you make sure that your brackets and braces are balanced. | |
The three types of brackets are parentheses ( ), braces { }, and square brackets [ ]. The first two are sometimes called round brackets and curly brackets.
When a bracketing character is unbalanced, the
Mathematica front end colors it purple:
If you try to evaluate an unbalanced expression,
Mathematica produces an error and highlights the location of the error. The cell bracket on the far right is also highlighted; it displays a + symbol that you can click to get more information about the error. In this case, no additional information is available, so clicking + does nothing:
When you type a closing bracket, the
Mathematica front end colors the matching opening bracket black and also momentarily highlights it. This helps you to see which bracketing symbols were just balanced:
Here, neither the opening square bracket nor the list brace is closed. The closing square bracket is used incorrectly instead of the closing list brace:
Making seemingly simple errors such as these can easily happen when you type long expressions:
The
Mathematica front end contains a menu item that is useful in these situations. With your cursor in the unbalanced expression, go to . The contents of the nearest matching pair of brackets are now selected. You can also do this by simply double-clicking in the unbalanced expression:
Repeated use of or repeated clicking further extends the selection to the next nearest matching set. You can quickly notice which bracketing character is not balanced:
You can also use to select the nearest pair of balanced brackets:
The position of the cursor is important when using . It will not work when the cursor is placed before an unbalanced bracketing character, because there is no balanced set of bracketing characters to select:
Triple-clicking a function head will extend the selection to determine the extent of that function. You can also do this by pressing
Ctrl+. twice with the cursor positioned somewhere in the function head:
Similarly, triple-clicking any delimiter, including quotations, will select its extent: