This is an example from Leonid Shifrin's tutorial:
testexpr = Expand[(1 + x)^10]
newexpr =
Replace[testexpr, {(a : _ : 1)*x^(y_?EvenQ) :> a*f[x^y],
a_ /; FreeQ[a, x] :> f[a]}, 1]
Basic question: what does (a : _ : 1) mean and do?
This is an example from Leonid Shifrin's tutorial:
testexpr = Expand[(1 + x)^10]
newexpr =
Replace[testexpr, {(a : _ : 1)*x^(y_?EvenQ) :> a*f[x^y],
a_ /; FreeQ[a, x] :> f[a]}, 1]
Basic question: what does (a : _ : 1) mean and do?
If you evaluate HoldForm@FullForm[a : _ : 1] you get Optional[Pattern[a,Blank[]],1]. This is a pattern object that will will be named a for later use and will be replaced by 1 if missing.
f[x] /. f[(a : _ : 1)] -> g[a] (* g[x] *)
f[] /. f[(a : _ : 1)] -> g[a] (* g[1] *)
FullForm[Hold[a : _ : 1]]might be instructive. – J. M.'s missing motivation Aug 18 '17 at 14:25Pattern. The Blank without preceding colon is a convenience that allows omitting parentheses when the low precedence of the colon would otherwise require them. – Alan Aug 18 '17 at 14:45