Re: matching nested heads
- To: mathgroup at smc.vnet.net
- Subject: [mg36284] Re: [mg36271] matching nested heads
- From: Andrzej Kozlowski <andrzej at lineone.net>
- Date: Fri, 30 Aug 2002 01:19:09 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
From the wording of your problem it is unclear if you are satisfied
with the output your own solution is giving you. I would have thought
not, since only one grandchild1[] with parent "parent1" and grandparent
"grandparent". is being matched. You can get a complete match by using
ReplaceRepeated instead of ReplaceAll:
In[33]:=
ttexpr//
.{grandparent[left1___,parent1[left2___,grandchild1[],right2___],
right1___]->
grandparent[left1,parent1[left2,MATCHED[],right2],right1]}
Out[33]=
grandparent[parent1[grandchild2[],MATCHED[],grandchild4[],MATCHED[]],
grandchild1[],
parent2[grandchild2[],grandchild1[],grandchild4[],grandchild1[]]]
exactly the same result can be achieved in a rather different way,
which may perhaps be seen as "more elegant".
In[34]:=
ttexpr /. expr_grandparent :>
(expr /. expr1_parent1 :> (expr1 /. expr2_grandchild1 :>
Matched[]))
Out[34]=
grandparent[parent1[grandchild2[], Matched[], grandchild4[],
Matched[]], grandchild1[], parent2[grandchild2[],
grandchild1[], grandchild4[], grandchild1[]]]
Andrzej Kozlowski
Toyama International University
JAPAN
On Thursday, August 29, 2002, at 06:37 AM, Sidney Cadot wrote:
> Hi all,
>
> In order to do some transformations on a tree I need to be able to
> replace
> an expression with head hdA if and if only its parent has head hdB and
> its
> grandparent had head hdC. Furthermore, the item itself and its parent
> may
> have any number sibling elements.
>
> What I do now is the following. Give the expression:
>
> ttexpr = grandparent[
> parent1[grandchild2[], grandchild1[], grandchild4[],
> grandchild1[]],
> grandchild1[],
> parent2[grandchild2[], grandchild1[], grandchild4[],
> grandchild1[]]];
>
> I apply a rule:
>
> ttexpr /. {
> grandparent[left1___, parent1[left2___, grandchild1[], right2___],
> right1___] ->
> grandparent[left1, parent1[left2, MATCHED[], right2], right1]}
>
> which gives the desired expression:
>
> grandparent[parent1[grandchild2[], MATCHED[], grandchild4[],
> grandchild1[]],
> grandchild1[],
> parent2[grandchild2[], grandchild1[], grandchild4[], grandchild1[]]]
>
>
> But I have the feeling that it should be possible to do this more
> elegantly.
> Does anybody have an idea in this respect?
>
> Best regards,
>
> Sidney Cadot
>
>
>
>
>
>