Function Repository Resource:

ReplaceContext

Source Notebook

Transform an expression by replacing all symbols in one context with symbols of the same name in another context

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["ReplaceContext"][expr,"context1`""context2`"]

gives expr with all symbols from "context1`" replaced with symbols in "context2`".

ResourceFunction["ReplaceContext"][expr,rules]

replaces the context with the list of rules.

ResourceFunction["ReplaceContext"][rules]

represents an operator form of ResourceFunction["ReplaceContext"] that can be applied to an expression.

Examples

Basic Examples (4) 

Retrieve the ResourceFunction:

In[1]:=
ResourceFunction["ReplaceContext"]
Out[1]=

Replace symbols in the current context with symbols in a new context:

In[2]:=
ResourceFunction[
 "ReplaceContext"][{a, b, c}, $Context -> "MyContext`"]
Out[2]=

Use a list of replacement rules:

In[3]:=
ResourceFunction[
 "ReplaceContext"][{a, b, c}, {$Context -> "MyContext`", "System`" -> "MySystem`"}]
Out[3]=

Use the operator form of ReplaceContext:

In[4]:=
replace = ResourceFunction[
  "ReplaceContext"][{$Context -> "MyContext`", "System`" -> "MySystem`"}]
Out[4]=
In[5]:=
replace[{f[x + y], g[z]}]
Out[5]=

Applications (2) 

Copy a definition to a different context:

In[6]:=
f[0] = 1;
f[x_Integer?Positive] := f[x] = f[x - 1]*x;
In[7]:=
Language`ExtendedFullDefinition[] = ResourceFunction["ReplaceContext"][
  Language`ExtendedDefinition[f], $Context -> "MySandbox`"]
Out[7]=

Now code can be run in the new context without modifying definitions in the current context:

In[8]:=
MySandbox`f /@ Range[5]
Out[8]=
In[9]:=
Definition[f]
Out[9]=
In[10]:=
Definition[MySandbox`f]
Out[10]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 12 October 2018

Related Resources

License Information