Is it possible to rename and block built-in functions temporarily? - wolfram-mathematica

I wish to temporarily rename a built-in symbol and use it with different name while block the main name of this symbol. For example, I wish the following code to print only "2" but not "1" and "3":
Block[{print = Print, Print}, Print[1]; print[2]; Print[3];]
In really the above code prints nothing.
Is it possible to make print working inside such code while completely block symbol Print?
Solutions like
With[{Print = f, print = Print}, Print[1]; print[2]; Print[3];]
are not suitable since Print is not really blocked inside such code.
The question appeared while thinking on a way to disable tracing of Message internals.

This is not very clean, but I believe it is serviceable.
Internal`InheritedBlock[{Print},
Unprotect[Print];
Print[x__] := Null /; ! TrueQ[$prn];
print[x__] := Block[{$prn = True}, Print[x]];
Print[1]; print[2]; Print[3];
]
If it is not acceptable to have the function replaced with Null in the return, you may need to use something like:
func[x__] := Hold[func[x]] /; ! TrueQ[$prn];
Followed by a ReleaseHold after the Block.
Or:
func[x__] := zz[x] /; ! TrueQ[$prn];
and then follow the Block with: /. zz -> func

Related

Why does _ destroy at the end of statement?

I've seen a few other questions and answers stating that let _ = foo() destroys the result at the end of the statement rather than at scope exit, which is what let _a = foo() does.
I am unable to find any official description of this, nor any rationale for this syntax.
I'm interested in a few inter-twined things:
Is there even a mention of it in the official documentation?
What is the history behind this choice? Is it simply natural fall-out from Rust's binding / destructuring rules? Is it something inherited from another language? Or does it have some other origin?
Is there some use-case this syntax addresses that could not have been achieved using explicit scoping?
Is it simply natural fall-out from Rust's binding / destructuring rules?
Yes. You use _ to indicate that you don't care about a value in a pattern and that it should not be bound in the first place. If a value is never bound to a variable, there's nothing to hold on to the value, so it must be dropped.
All the Places Patterns Can Be Used:
match Arms
Conditional if let Expressions
while let Conditional Loops
for Loops
let Statements
Function Parameters
Is there even a mention of it in the official documentation?
Ignoring an Entire Value with _
Of note is that _ isn't a valid identifier, thus you can't use it as a name:
fn main() {
let _ = 42;
println!("{}", _);
}
error: expected expression, found reserved identifier `_`
--> src/main.rs:3:20
|
3 | println!("{}", _);
| ^ expected expression
achieved using explicit scoping
I suppose you could have gone this route and made expressions doing this just "hang around" until the scope was over, but I don't see any value to it:
let _ = vec![5];
vec![5]; // Equivalent
// Gotta wait for the scope to end to clean these up, or call `drop` explicitly
The only reason that you'd use let _ = foo() is when the function requires that you use its result, and you know that you don't need it. Otherwise, this:
let _ = foo();
is exactly the same as this:
foo();
For example, suppose foo has a signature like this:
fn foo() -> Result<String, ()>;
You will get a warning if you don't use the result, because Result has the #[must_use] attribute. Destructuring and ignoring the result immediately is a concise way of avoiding this warning in cases where you know it's ok, without introducing a new variable that lasts for the full scope.
If you didn't pattern match against the result then the value would be dropped as soon as the foo function returns. It seems reasonable that Rust would behave the same regardless of whether you explicitly said you don't want it or just didn't use it.

Deleting first and last array element in one line?

How can I delete the first and last element in one line in a clever way?
I've tried:
names = %w[Go Go Go Power Rangers Go]
names.shift.pop
This fails because, I believe, both shift and pop return the value removed, which is then passed onto the following function, raising an error.
I also tried to make this work with delete_at, but it does not allow an array parameter and thus I get no further in my quest to make this a one-liner.
Any ideas?
Note: I value minimalism
_, *names, _ = %w[Go Go Go Power Rangers Go]
names #=> ["Go", "Go", "Power", "Rangers"]
Or if you already have the whole array as names, then:
names = %w[Go Go Go Power Rangers Go]
_, *names, _ = names
names #=> ["Go", "Go", "Power", "Rangers"]
You can use names = names[1..-2], but you shouldn't. Just use names.pop; names.shift and be done with it.
How about this?
names.slice!(1..-2)
Really though, as others have said, there's nothing wrong with:
names.pop
names.shift
I really like this solution:
_, *names, _ = names
It is very cool, is not it?
Also, I would use another variable (funcional style)
_, *new_names, _ = names
Edit: Sorry I realised that #sawa already post this solution.

Local variable and Block usage

I wrote code that executes a function it receives from the (future) client, in a loop with some parameters. will call it func(name it).
Inside the function the client usually generate expression in the same variables(by GetUncertainty - each variable must be cleared before use). To do so , the simple idea is to use Block. Later , a code is executed that handles di and i outside the function.So, di and i must be globals(there could be more, it is flexible).
BTW, I know it is not efficient, but efficiency is not an issue.
func[v_, a_, r_] :=
(V = v; A = a; R = r;
Block[{V, A, R},i = V A + A 10 + R 100; di = GetUncertainty[i, {V, A, R}];] ;
Print[di])
The problem is that the client must reset the vars by hand. That means that the function parameters can't be V_,A_,R_ , otherwise The vars in the block will be replace by the values. I didn't manage to overcome this in any other way.
Another question in a similar issue. if I have
vars = {V,A,R,DR} , then
Block[vars , ..code.. ] , throws error that it is not a list.whereas Block[ {V,A,R,DR},..code..] works. How to overcome this?
Thanks.
its hard to unravel what you are trying to do, but the best approach may be to simply never assign values to symbols that need to be used as pure symbols in some context. Then you don't even need the Block[].
func[v_, a_, r_] := (
i = V A + A 10 + R 100;
di = GetUncertainty[i, {V, A, R}];
Print[di /. {V->v,A->a,R->r])
starting your own symbol names with Caps is frowned upon by the way as you risk conflict with built in symbols.
Note also there is a dedicated site mathematica.stackexchange.com
If I understand your application what you need are Formal Symbols. These are a set of Symbols with the Attribute Protected so that they cannot accidentally be assigned a value. They may be entered with e.g. Esc$AEsc for Formal Capital A. You can then use ReplaceAll (short form /.) as george showed to substitute your desired values.
Your code would be something like this:
func[v_, a_, r_] :=
Module[{i, di},
i = \[FormalCapitalV] \[FormalCapitalA] + \[FormalCapitalA] 10 + \[FormalCapitalR] 100;
di = GetUncertainty[i, {\[FormalCapitalV], \[FormalCapitalA], \[FormalCapitalR]}];
di /. {\[FormalCapitalV] -> v, \[FormalCapitalA] -> a, \[FormalCapitalR] -> r}
]
That looks horrible here but in a Notebook it looks like this:
I included Module to show how you should properly localize utility Symbols such as i and di but this particuarly simple function could also be written without them:
Your second question regarding "vars = {V,A,R,DR} then Block[vars , ..code.. ]" is answered here: How to set Block local variables by code?
Dedicated StackExchange site:

Possible to block OwnValues when DownValues already exist?

For cases where one has already assigned DownValues associated with the name 'a', is there an accepted way to block the assignment of OwnValues to the same name? (I originally came across this issue while playing with someone's attempt at implementing a data dictionary.)
Here's what I mean to avoid:
Remove[a];
a[1] := somethingDelayed
a[2] = somethingImmediate;
DownValues[a]
a[1]
a[2]
Returns...
{HoldPattern[a[1]] :> somethingDelayed,
HoldPattern[a[2]] :> somethingImmediate}
somethingDelayed
somethingImmediate
And now if we were to evaluate:
a = somethingThatScrewsUpHeads;
(* OwnValues[a] above stored in OwnValues *)
a[1]
a[2]
We get...
somethingThatScrewsUpHeads[1]
somethingThatScrewsUpHeads[2]
Is there an easy/flexible way to prevent OwnValues for any Name in DownValues? (Lemme guess... it's possible, but there's going to be a performance hit?)
I don't know if this is an "accepted" way, but you could define a rule that prevents Set and SetDelayed from acting upon a:
Remove[a];
a[1] := somethingDelayed
a[2] = somethingImmediate;
a /: HoldPattern[(Set|SetDelayed)[a, _]] := (Message[a::readOnly]; Abort[])
a::readOnly = "The symbol 'a' cannot be assigned a value.";
With this rule in place, any attempt to assign an OwnValue to a will fail:
In[17]:= a = somethingThatScrewsUpHeads;
During evaluation of In[17]:= a::readOnly:
The symbol 'a' cannot be assigned a value.
Out[17]= $Aborted
In[18]:= a := somethingThatScrewsUpHeads;
During evaluation of In[18]:= a::readOnly:
The symbol 'a' cannot be assigned a value.
Out[18]= $Aborted
However, this rule will still allow new DownValues for a:
In[19]:= a[3] = now;
a[4] := later
In[20]:= a[3]
Out[20]= now
In[21]:= a[4]
Out[21]= later
Performance
The rule does not seem to have an appreciable impact on the performance of Set and SetDelayed, presumably since the rule is installed as an up-value on a. I tried to verify this by executing...
Timing#Do[x = i, {i, 100000000}]
... both before and after the installation of the rule. There was no observable change in the timing. I then tried installing Set-related up-values on 10,000 generated symbols, thus:
Do[
With[{s=Unique["s"]}
, s /: HoldPattern[(Set|SetDelayed)[s, _]] :=
(Message[s::readOnly]; Abort[])
]
, {10000}]
Again, the timing did not change even with so many up-value rules in place. These results suggest that this technique is acceptable from a performance standpoint, although I would strongly advise performing performance tests within the context of your specific application.
I am not aware of any way to directly "block" OwnValues, and since Mathematica's evaluator evaluates heads before anything else (parts, application of DownValues, UpValues and SubValues, etc), this does not bring us anywhere (I discussed this problem briefly in my book).
The problem with a straightforward approach is that it will likely be based on adding DownValues to Set and SetDelayed, since it looks like they can not be overloaded via UpValues.
EDIT
As pointed by #WReach in the comments, for the case at hand UpValues can be successfully used, since we are dealing with Symbols which must be literally present in Set/SetDelayed, and therefore the tag depth 1 is sufficient. My comment is more relevant to redefining Set on some heads, and when expressions with those heads must be allowed to be stored in a variable (cases like Part assignments or custom data types distinguished by heads)
END EDIT
However, adding DownValues for Set and SetDelayed is a recipe for disaster in most cases ( this thread is very illustrative), and should be used very rarely (if at all) and with extreme care.
From the less extreme approaches, perhaps the simplest and safest, but not automatic way is to Protect the symbols after you define them. This method has a problem that you won't be able to add new or modify existing definitions, without Unprotect-ing the symbol.
Alternatively, and to automate things, you can use a number of tricks. One is to define custom assignment operators, such as
ClearAll[def];
SetAttributes[def, HoldAll];
def[(op : (Set | SetDelayed))[lhs_, rhs_]] /;
Head[Unevaluated[lhs]] =!= Symbol || DownValues[lhs] === {} :=
op[lhs, rhs]
and consistently wrap SetDelayed- and Set-based assignments in def (I chose this syntax for def - kept Set / SetDelayed inside def - to keep the syntax highlighting), and the same for Set. Here is how your example would look like:
In[26]:=
Clear[a];
def[a[1]:=somethingDelayed];
def[a[2]=somethingImmediate];
def[a=somethingThatScrewsUpHeads];
In[30]:= {a[1],a[2]}
Out[30]= {somethingDelayed,somethingImmediate}
You can then go further and write a code - processing macro, that will wrap SetDelayed- and Set-based assignments in def everywhere in your code:
SetAttributes[useDef, HoldAll];
useDef[code_] := ReleaseHold[Hold[code] /. {x : (_Set | _SetDelayed) :> def[x]}]
So, you can just wrap your piece of code in useDef, and then don't have to change that piece of code at all. For example:
In[31]:=
useDef[
Clear[a];
a[1]:=somethingDelayed;
a[2]=somethingImmediate;
a=somethingThatScrewsUpHeads;
]
In[32]:= {a[1],a[2]}
Out[32]= {somethingDelayed,somethingImmediate}
In the interactive session, you can go one step further still and set $Pre = useDef, then you won't forget to wrap your code in useDef.
EDIT
It is trivial to add diagnostic capabilities to def, by using the pattern - matcher. Here is a version that will issue a warning message in case when an assignment to a symbol with DownValues is attempted:
ClearAll[def];
SetAttributes[def, HoldAll];
def::ownval =
"An assignment to a symbol `1` with existing DownValues has been attempted";
def[(op : (Set | SetDelayed))[lhs_, rhs_]] /;
Head[Unevaluated[lhs]] =!= Symbol || DownValues[lhs] === {} := op[lhs, rhs]
def[(Set | SetDelayed)[sym_, _]] :=
Message[def::ownval, Style[HoldForm[sym], Red]];
Again, by using useDef[] (possibly with $Pre), this can be an effective debugging tool, since no changes in the original code are at all needed.

Issue w/ Symbol Substitution in Mathematica

I want to define a symbol and use it within a function. For example, with IDnumbers defined as a list of numbers:
ParallelMap[{#1, Name[#1], Age[#1]} &, IDnumbers]
With userlist={#1, Name[#1], Age[#1]} becomes:
ParallelMap[userlist &, IDnumbers]
It works just fine with the list itself in the code, but not with the symbol. The same thing happens with a list of strings vs. a symbol assigned to a list of strings. Why is this?
Since f[#]& is shorthand for Function[f[#]] you should always complete your anonymous function with a trailing & to get a working function.
In your example:
userlist={#1, Name[#1], Age[#1]}&
ParallelMap[userlist, IDnumbers]
More thorough explanation:
By just using something like f[#] you get (in FullForm[])
In[15] := f[#] // FullForm
Out[15]//FullForm = f[Slot[1]]
whereas this gets transformed to a Function by the trailing & operator:
In[16] := f[#]& // FullForm
Out[16]//FullForm = Function[f[Slot[1]]]
If you do this in two steps, & doesn't evaluate the intermediate variable expr:
In[25]:= expr = f[#]//FullForm
In[26]:= expr &
Out[25]//FullForm = f[Slot[1]]
Out[26] = expr &
You can force the evaluation of expr before it gets wrapped in the Function[] by using Evaluate[]:
In[27]:= expr=f[#]//FullForm
In[28]:= Evaluate[expr]&
Out[27]//FullForm = f[Slot[1]]
Out[28] = f[Slot[1]]&
Another way is to supply the Function[] wrapper yourself:
userlist={#1, Name[#1], Age[#1]}
ParallelMap[Function[userlist], IDnumbers]
Personally, i would consider this bad coding style. Just get used to always finishing an anonymous function with a trailing & like you would supply a closing paranthesis ) to a corresponding opening one (.
Edit
Ok, in your case of a dynamically generated anonymous function i can see why you couldn't supply the & directly. Just wrap the expression with the Slot[]s in a Function[] instead.

Resources