0
$\begingroup$

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?

$\endgroup$

2 Answers 2

3
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ +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. $\endgroup$ Dec 27, 2013 at 15:34
2
$\begingroup$

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 :).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.