First, Let use see
a = {"wx", "wy", "wz"};
AssociationThread[Flatten[StringCases[a, "w" ~~ d_ :> d]] -> a]
gives
<|"x" -> "wx", "y" -> "wy", "z" -> "wz"|>
Now comes the weird thing. Define
ClearAll[test];
test[] := Module[{a},
a = {"wx", "wy", "wz"};
AssociationThread[Flatten[StringCases[a, "w" ~~ d_ :> d]] -> a]
]
and run test[]
, gives
<|d -> "wz"|>
Why?
If you look at the test[]//Trace
, you will find "w" ~~ d$_ :> d
appears. What is d$_
?
If we define
ClearAll[test];
test[] := Module[{},
a = {"wx", "wy", "wz"};
AssociationThread[Flatten[StringCases[a, "w" ~~ d_ :> d]] -> a]
]
or
ClearAll[test];
test[] := Module[{a,dList},
a = {"wx", "wy", "wz"};
dList = Flatten[StringCases[a, "w" ~~ d_ :> d]];
AssociationThread[dList -> a]
]
then test[]
gives correct answer.
Can someone explain the above behaviour? How could Module a
variable affect the rule replacement of d
?
Flatten[StringCases[a,"w"~~d_:>d]]->a
inside the module you get{d,d,d}->{"wx","wy","wz"}
. It looks like what's happening is something is broken when module isolatesd
. I don't know why it's isolatingd
, seems to be due to the->a
. Normallya$123
is used to create a unique version of scoped variables in things likeModule
. Becaused_
becomesd$_
the rule is replacing with the actual symbold
and not the matchedd$
. The association is then merging the degenerate values for the keyd
. This looks like a bug to me, I'd report it. $\endgroup$AssociationThread
is irrelavent $\endgroup$