Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Wrapping Begin["Context`"], ..., End[] into a function

5 views
Skip to first unread message

Leo Alekseyev

unread,
Dec 31, 2009, 3:15:31 AM12/31/09
to
Dear Mathgroup,

I was wondering if it's possible to write a function that evaluates an
expression in a particular context. In other words, instead of
writing this:

cpsave = $ContextPath;
Begin["Materials1`"];
$ContextPath = {"Materials1`", "System`"};
myExpression;
End[];
$ContextPath = Global`cpsave;

I would like to be able to make a function call, e.g.
evaluateInContext["Materials1`",myExpression]

The naive solution of
evaluateInContext[cont_,expr_]:=(
cpsave = $ContextPath;
Begin[cont];
...
)

doesn't work because any symbol in parentheses is bound to the current
context before any evaluation takes place. Is there a trick to make
this work?

Thanks, and happy New Year to all!

--Leo

Vince Virgilio

unread,
Jan 1, 2010, 5:38:37 AM1/1/10
to
On Dec 31 2009, 3:15 am, Leo Alekseyev <dnqu...@gmail.com> wrote:
> Dear Mathgroup,
>
> I was wondering if it's possible to write a function that evaluates an
> expression in a particular context. In other words, instead of
> writing this:

SNIP


I wondered about the same a few months ago:

http://tinyurl.com/yjhn72l

(Leonid Shifrin gave a helpful response.)


Vince Virgilio

dh

unread,
Jan 1, 2010, 5:35:04 AM1/1/10
to
Hi Leo,
to prevent defining symbols before the correct context has been
established, you may e.g. give your expression as a string:

Remove[f, x];

make[con_, myExp_] := (
BeginPackage[con];
Print["context=", $Context];
ToExpression@myExp;
EndPackage[];
)

make["con1`", "f[x_]:=x^2"]

Daniel

0 new messages