2
$\begingroup$

Let us say we have two sets of symbols $(x, y, z)$ with the same names that live in two different contexts:

{context1`x,context1`y,context1`z} = {1, 10, 100}

{context2`x,context2`y,context2`z} = {2, 20, 200}

How can we define a function which takes as an argument a context name, adds $x$ and $y$ that live in the specified context and assigns the result to $z$ in the same context?

Example:

f["context1`"]

would result in

{context1`x, context1`y, context1`z} = {1 ,10, 11}

{context2`x, context2`y, context2`z} = {2, 20, 200}
$\endgroup$
3
  • $\begingroup$ So there will be always only 3 symbols in given context? $\endgroup$
    – Kuba
    Sep 8 '13 at 20:31
  • $\begingroup$ I think he is trying to force data structures into M. x,y,z are properties of the contextN` object and I've shown how to define methods (adding two parameters) and set for the properties. $\endgroup$ Sep 8 '13 at 20:45
  • $\begingroup$ I am indeed using contexts like data structures. I am looking for a generic way to make a function work on symbols of a context given in argument. Inside the definition of the function I would like to be able to use directly the symbols (no Strings). $\endgroup$
    – Quiberion
    Sep 8 '13 at 21:03
1
$\begingroup$
{context1`x, context1`y, context1`z} = {1, 10, 100}
f[input_String] := (
  input <> "z" <> "=" <> 
    ToString[
      ToExpression[input <> "x"] + ToExpression[input <> "y"]
    ]
  ) //ToExpression
f["context1`"]
context1`z

EDIT: now that we've established that we are trying to define methods on structures, let's create general get and set functions. Then the methods that operate on those parameters can be written in terms of get and set directly or in Modules.

set[context_String, var_String, val_] :=
  ToExpression[context <> var <> "=" <> ToString[val]];

get[context_String, var_String] := 
  ToExpression[context <> var]

f[input_String] := Module[{
   x = get[input, "x"],
   y = get[input, "y"],
   z
   },
   z = x + y;
   set[input, "z", z]
]
g[input_String]:=set[input,"z",get[input,"x"]+get[input,"y"]]
$\endgroup$
0
$\begingroup$

How can we define a function which takes as an argument a context name, adds x and y that live in the specified context and assigns the result to z in the same context?

Keep the body of your function as a String (or Boxes, if necessary), and then:

f[context_String] := (Begin[context]; ToExpression["z=x+y"]; End[])

f["foo`"];

Definition[foo`z]
foo`z = foo`x + foo`y

Edit: this assumes no global ($ContextPath) definitions for x, y, or z, which I now realize isn't too good. No time to fix it however.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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