Why aren't parentheses ( ) an expression in Mathematica?
Can I get an expression in a form where parentheses are represented by an expression?
Answer
As djp explains parentheses are unnecessary in the FullForm
of an expression; it is logical for superfluous information to be removed.
However if you want parentheses to persist you could use something like this:
$PreRead = # /. RowBox[{"(", body___, ")"}] :> RowBox[{"paren", "[", body, "]"}] &;
MakeBoxes[paren[body___], form_] :=
MakeBoxes[{body}, form] /.
RowBox[{"{", x___, "}"}] :> RowBox[{"(", x, ")"}]
Now:
foo[(bar), (1 + 2) + 5]
foo[(bar), 5 + (3)]
The FullForm
of which is: foo[paren[bar], Plus[5, paren[3]]]
Also:
(1, 2, 3)
% // FullForm
(123)
paren[1,2,3]
()
% // FullForm
()
paren[]
You could add rules as desired to handle the head paren
.
Note: before taking this rather unusual step consider using the existing functionality of AngleBracket
.
Sidebar: Box form manipulation
LLlAMnYP commented:
I'm even surprised that the replacement rules in the answer below work at all. It prompts me to ask "how does M even apply replacement rules before parsing the expression?"
To understand what is being done with $PreRead
and MakeBoxes
and the rules on RowBox
one must understand how Box form is used by Mathematica. As the documentation states:
All textual and graphical forms in Mathematica are ultimately represented in terms of nested collections of boxes.
Input is converted into Boxes by the Front End using functionality that may be accessed by this method that John Fultz revealed, which I package as:
parseString[s_String, prep : (True | False) : True] :=
FrontEndExecute[FrontEnd`UndocumentedTestFEParserPacket[s, prep]]
For example:
parseString @ "(1,2,3)"
{BoxData[RowBox[{"(", RowBox[{"1", ",", "2", ",", "3"}], ")"}]], StandardForm}
This Box data is then sent to the Kernel where $PreRead
, if defined, is applied before further processing. (Note: CellEvaluationFunction
is a lower level hook that is applied before $PreRead
.)
Recalling that "all textual and graphical forms ... are ... represented in ... boxes" the output expression must be converted back to Box form before it is sent to the Front End for display, and MakeBoxes
lets us attach rules to this process. It is more flexible than Format
and more robust when we want to use output as input as Michael Pilat explained.
Comments
Post a Comment