I'm trying to make a function f
that takes a symbol, a value, and a context, and creates the symbol in the requested context and assigns it the passed value. The obvious doesn't work. I.e.:
Attributes[f]={HoldAllComplete};
f[symbol_,value_,context_]:=(Begin[context];Set[symbol,value];End[])
Creates the symbol in the current context, as opposed to the one that is passed as an argument. This seems to happen because the FrontEnd, as soon as it sees f
getting evaluated, creates the symbol in the current context despite HoldAllComplete
. I tried adding Remove[symbol]
to the function but that doesn't work. Any thoughts?
Answer
The problem is that if you pass a symbol, it will be created already during the parsing stage, when you pass it, in the current context. Therefore I suggest to pass its string name instead. This function will do the job:
ClearAll[f];
f[symbolName_String, value_, context_] :=
Block[{$ContextPath},
BeginPackage[context];
ToExpression[
symbolName,
StandardForm,
Function[name, Set[name, value], HoldAll]
];
EndPackage[]
]
for example
f["a", 10, "Test`"]
Test`a
(* 10 *)
If you still want to pass a symbol, you can use this:
ClearAll[f];
f[symbol_, value_, context_] :=
With[{set = MakeBoxes[symbol = value]},
Block[{$ContextPath},
BeginPackage[context];
ReleaseHold[MakeExpression@set];
EndPackage[]]];
which is a version of the code I used here. But be aware that you will also create the symbol symbol
in the current working context, so you may additionally use Remove
to remove it.
So, for example:
f[a, 20, "Test`"]
Test`a
(* 20 *)
Comments
Post a Comment