Skip to main content

Position of a pattern-matched part of an expression



What you have




  1. A pattern, with certain part of it labeled


    As an example — Label: wally


    pattern = h : HoldPattern@f[x, __, 3[5], wally_, y]


  2. An expression that matches a pattern such as:


    expr = f[x, 9, v, h[v], 3[5], v, y]



What I want


The position of the part of the expression expr that matched the label wally.


In the above example, that would be


gimmeWhattaWanna[expr, pattern, wally]
(* {{6}} *)

Note


If the labeled pattern is a sequence such as wally__, either finding the position of the first, or the first and last, are acceptable. If the labeled pattern is repeated such as in f[wally_, 2, wally_], then a list of the positions seems the most natural solution. However, a solution that limits itself to non-repeated labels, or even non-sequence ones is useful.





Comments