Currently, I have a nested list of rules of the form
lst1={1->a,2->{3->c,4->d,5->{6->f,7->{8->h,...}}}}
(where I don't know the length of the list). I would like to apply some function z
to the "first" elements of the rules to get something of the form
lst2={z[1]->a,z[2]->{z[3]->c,z[4]->d,z[5]->{z[6]->f,z[7]->{z[8]->h,...}}}}.
Here's a little bit more info about the problem:
- I don't know the length of the (nested) list.
- A priori, I also don't know the lengths of any of the inner lists. That means both
{1->a,2->{3->c,4->d,5->{6->f,7->{8->h,...}}}}
and{1->a,2->b,3->{4->d,5->{6->f,7->{8->h,...}}}}
are equally possible / valid.
Basically, I want everything of the form Rule[_,_]
to be mapped to Rule[z[_],_]
, but nothing I attempted (including Apply
, MapAt
, etc.) seems to work. I can't figure out the pattern matching to save my life.
One thing I thought would work is doing
lst1 /. {Rule[x_,y_]:>Rule[z[x],y]},
but this fails for inputs of the form lst3={1 -> {2 -> {3 -> {4 -> 5}}}}
. For lst3
as above, I would want to get out
lst4={z[1]->{z[2]->{z[3]->{z[4]->5}}}},
but instead I get lst4b={z[1] -> {2 -> {3 -> {4 -> 5}}}}
.
Please help!