hehe very good point helios!
Nonetheless, adding logic to the rules and making them more complicated can also handle context:
Besides the preceding rules, do:
"||", "Expression" (of value x), "|", X
if (X!="|"
&& X!=emptyToken)
->"|", "Expression" (of value AbsoluteValue(x)), X
Btw, in my calculator grammar I do have non-context free expressions:
I use {{a}} to denote bounded variable, but I also use "{" as a regular bracket delimiter: x^{{a+b}*b}.
I use tricks such as the preceding one to handle context. It is a bit tougher to do, but the overall benefit of handling real world mathematical notation is immense (when I write an article, I copy and paste directly from LaTeX to the calculator and back, which is a huge time saver).
[Edit:] Another interesting point: in LaTeX, \\ is used to make a new line: great to use for long algebraic expressions. So, if the parser sees token "\\", it should just pop it out of the stack (i.e. ignore it). However, if "\\" is inside a matrix, it becomes a non-trivial token, equivalent to the "," token (in my calculator, you can either give a matrix as the comma-separated list of rows, or as the LaTeX equivalent:
((0,1),(1,0))
or
\begin{array}{cc} 0 & 1 \\ 1 & 0\end{array}
)
So, I actually have to "count context" (number of non-closed \begin{array} occurrences), in order to know whether the "\\" token should be discarded or used as a row separator. You could say that my parser has a single register (incrementing/decrementing number of non-closed \begin{array}).
[Edit:] I actually haven't implemented the above register: been thinking to do it for a while: will do right now!
[Edit:] Just added a LogParsing token to the parser >:)
So, here are the simplification rules for the example I was mentioning, very similar to chisname's:
{{a}}+b
should be parsed as BoundVariable(a)+b,
while {{{a}+{b}}} should be parsed just as a+b.
I must note that the new code doing that is quite ugly - and my old code was wrong - discovered the mistake after the discussion here. The code is ugly in the sense that I do something quite criminal - under a special condition I push back the top token.
1 2 3
|
%LogParsing
{{{a}}+b};
{{a}+{b}}
| |
http://vector-partition.jacobs-university.de/vpf/cgi-bin/calculator?textInput=%25LogParsing%0D%0A%7B%7B%7Ba%7D%7D%2Bb%7D%3B+%0D%0A%7B%7Ba%7D%2B%7Bb%7D%7D%0D%0A