Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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}
share|improve this question
    
So there will be always only 3 symbols in given context? –  Kuba Sep 8 '13 at 20:31
    
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. –  Timothy Wofford Sep 8 '13 at 20:45
    
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). –  Quiberion Sep 8 '13 at 21:03
add comment

2 Answers

up vote 1 down vote accepted
{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"]]
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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