0

Problem of RuleDelayed

NameList = {"a", "b", "c", "d"};

rules = Table[NameList[[i]] <> "=" ~~ x__ ~~ "\n" :> NameList[[i]] <> 
              "=" ~~ OptionValue["Position"] ~~ "\n", {i, Length@NameList}];

output of rules[[1]] is

a=~~x__~~  :>NameList[[i]]<>=~~OptionValue[Position]~~

Here, since I used RuleDelayed, NameList in the right-hand side is not evaluated.

One workaround is to use Rule, but Rule may cause some warning errors concerning not a string.

rules = Table[k = i; NameList[[i]] <> "=" ~~ x__ ~~ "\n" -> NameList[[k]] <> "=" ~~ 
              OptionValue["Position"] ~~ "\n", {i, Length@NameList}];

rules[[1]]

(*
    a=~~x__~~->a=~~OptionValue[Position]~~
*)

How to solve that in the RuleDelayed case? the effect like the Rule case?

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
HyperGroups
  • 8,619
  • 1
  • 26
  • 63

2 Answers2

3

If your example is representative I would just use this:

NameList = {"a", "b", "c", "d"};

(# <> "=" ~~ x__ ~~ "\n" :> # <> "=" ~~ OptionValue["Position"] ~~ "\n") & /@ NameList
{"a=" ~~ x__ ~~ "
   " :> "a" <> "=" ~~ OptionValue["Position"] ~~ "
   ", "b=" ~~ x__ ~~ "
   " :> "b" <> "=" ~~ OptionValue["Position"] ~~ "
   ", "c=" ~~ x__ ~~ "
   " :> "c" <> "=" ~~ OptionValue["Position"] ~~ "
   ", "d=" ~~ x__ ~~ "
   " :> "d" <> "=" ~~ OptionValue["Position"] ~~ "
   "}

If for some reason you must use Table see: Function in Table. RuleDelayed also has a hold attribute, like Function, so the cause and solutions are the same.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • +1, much nicer than mine. The "anonymity" of # prevents variable name trouble here. Compare with Function[yyy, (yyy <> "=" ~~ x__ ~~ "\n" :> yyy <> "=" ~~ OptionValue["Position"] ~~ "\n")] /@ NameList where x$__ occurs in the output. Somehow a good refresher for me. – Jacob Akkerboom Dec 27 '13 at 15:34
2

Kind of writing With in terms of ReplaceAll in order to avoid problems with ugly variable names in scoping constructs, we can write

ClearAll[rules]
rules =
  Table[
   ReplaceAll[
    Unevaluated[
     nl <> "=" ~~ x__ ~~ "\n" :> 
      nl <> "=" ~~ OptionValue["Position"] ~~ "\n"
     ],
    HoldPattern@nl -> NameList[[i]]
    ]
   ,
   {i, Length@NameList}
   ]

Output

enter image description here

I suppose one slight difference is that "a"<>"=" did not become "a=", as is the case when you used Rule. It would be nicer if the strings were joined, but yeah I think this is fine :).

Jacob Akkerboom
  • 12,215
  • 45
  • 79