The documentation says that expr& has lower precedence than expr1 /. expr2. Thus, parsing should start from operators with the lowest precedence, like FormBox, and then reach deep into the parse tree, all the way down to operators with high precedence, like raw symbols and numbers.
By this logic, a&/.b should be parsed like this:
- Attempt to parse
FormBox, thenCompoundExpression, down to the lambdaexpr&. a&is parsed asFunction[a].- We're done, but there's
/.bleft to parse. Yet there are no rules for(expr1 &) /. expr2sinceexpr&has lower precedence thanexpr1 /. expr2. - Thus,
a&/.bshould be a syntax error.
I imagine an EBNF grammar for this "lambda+ReplaceAll with symbols" mini-language like this:
start: function
function: replace_all
| function "&"
replace_all: symbol
| replace_all "/." symbol
symbol: /[a-zA-Z][0-9a-zA-Z]*/
Apparently, this is incorrect since the Wolfram Language can parse this:
Hold[a & /. b] // TreeForm
Turns out, a&/.b parses as (a&) /. b. Doesn't this mean that expr& has higher precedence than expr1 /. expr2?
c/.d& parses as I'd expect:
- Try to parse
expr1&. - Here
expr1isc/.d. - Try to parse
expr1as something with a higher precedence, likeAddTo,SubtractFromorReplaceAll. expr2 /. expr3matches, so we getexpr2 == candexpr3 == d.
Thus, the tree is:
Needs["CodeParser`"]
CodeParse["(a&/.b);(c/.d&)"] //. {
ContainerNode[_, {a_}, _] -> a,
LeafNode[_, a_, _] -> a,
CallNode[head_, {args__}, _] -> head[args]
} // TreeForm
The left subtree is for a&/.b (which doesn't make sense) and the right subtree is for c/.d& (which seems fine).
- Why does
a & /. bparse at all ifa &has lower precedence thanx /. y? - What could a proper (E)BNF grammar for the mini-language of lambdas and
ReplaceAlls look like?


a&has lower precedence, I parse it first, and that's it, there's no grammar to match/.b. Is this understanding incorrect? Also, sincea&/.bis parsed as(a&)/.b, doesn't this imply thata&has higher precedence thanx/.y? For this to work, I'd need to parse the binary/.operator first, followed by the unary&operator, right? $\endgroup$a&/.bis parsed as(a &) /. b, which operator has higher precedence:&or/.? It seems to me that&has higher precedence, but the documentation says otherwise. Where's my mistake? $\endgroup$&is a postfix operator, and/.is an infix operator. Imagine a similar example withDerivativeandMap. Looking at the Operator Precedence Table,/@has a higher precedence than', yetf'/@{1, 2, 3}is parsed as expected to{Derivative[1][f][1], Derivative[1][f][2], Derivative[1][f][3]}. Similarly,+(infix) has higher precedence than¬(prefix), yetp+¬qis parsed ("as expected") toPlus[p,Not[q]]. $\endgroup$