Position
returns lists of numbers consumed by Extract
, ReplacePart
and others as "positions" in arbitrarily complex forms. This works great:
Position[x+f[x],x]
--> {{1}, {2, 1}}
, 2 matches, each of which can be fed to Extract[x+f[x],{1}]
--> x
and to ReplacePart[x+f[x],{2,1}->y]
-->x+f[y]
.
However, there seems to be a hiccup when matching the whole input expression. Position[x+f[x],x+f[x]]
--> {{}}
. This is documented behavior: "A part specification {} returned by Position represents the whole of expr."
But... Extract[x+f[x],{}]
--> {}
, which seems clearly wrong (there isn't an empty list anywhere in x+f[x]
). Interestingly, Extract[x + f[x], {{}}]
--> {x + f[x]}
works; this is the "extract a list of positions" syntax. But this breaks the easy connection between Position
and Extract
without using an awkward "ask for a list of one then take the first answer" work-around.
Even worse, ReplacePart[x + f[x], {} -> y]
--> x + f[x]
, i.e. no replacement, while ReplacePart[x + f[x], {{}} -> y]
--> y
-- ReplacePart
seems to want a special {{}}
form for the whole. (Note that this isn't ReplacePart's multiple-value syntax, which also doesn't work: ReplacePart[x + f[x], {{} -> y}]
--> x + f[x]
, and so there's no easy work-around to make this work here.
So... what's going on here? Both Extract
and ReplaceParts
are documented to use Position
's output, but neither does when it comes to the whole. Is there a principled approach to take? (Right now, I'm just special-casing this, but that seems utterly unsatisfying...)
Thanks -- perry