From: dh on


Leo Alekseyev wrote:

> Dear Mathgroup,

>

> I am trying to understand what happens when a pattern from function

> definition appears in the list of replacement rules. In particular,

> consider this:

>

> (* Example (A): *)

> Clear[foo,kij,k];

> foo[k_] := kij /. {kij :> Table[k[[i]] k[[j]], {i, 1, 3}, {j, 1, 3}]}

> foo[{1, 1, 1}]

> (* gives {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} as expected *)

>

> (* But now, let's put replacement rules into a variable: *)

> (* Example (B): *)

> rrules := {kij :> Table[k[[i]] k[[j]], {i, 1, 3}, {j, 1, 3}]}

> foo[k_] := kij /. rrules

> foo[{1, 1, 1}]

> (* rrules gets evaluated first, hence this fails *)

>

> My question is -- is there a good way to control evaluation such that

> even though rules are defined in a variable, evaluation proceeds as in

> Example (A)?

>

> Below are a couple of things I found to work, but they are somewhat

> syntactically cumbersome.

>

> (* Example (C): works, but have to manually turn off messages *)

> foo[k_] := Evaluate[Off[Part::"partd"]; kij /. rrules]; On[

> Part::"partd"]

> foo[{1, 1, 1}]

>

> (* Example (D): works, but have to rename function argument and wrap

> in a block *)

> foo[kk_] := Block[{k = kk}, kij /. rrules];

> foo[{1, 1, 1}]

>

> Thanks,

> --Leo

>

Hi Leo,

in: rrules := {kij :> Table[k[[i]] k[[j]], {i, 1, 3}, {j, 1, 3}]}

k is a global variable, but in: foo[k_] := kij /.... k it is la local one.



What you can do is to make k local in both cases. E.g.:



Clear[foo, kij, k];

rrules[k_] := {kij :> Table[k[[i]] k[[j]], {i, 1, 3}, {j, 1, 3}]}

foo[k_] := (kij /. rrules[k])

foo[{1, 1, 1}]



Daniel