11
$\begingroup$

As far as I understand, I cannot define the values of built-in functions: Sin[Cat] := Dog will result in error. This is because all built-in symbols have attribute Protected.

However for the function N[], which is also protected, I can define a custom value:

N[Cat] := Dog

By the way, doing so will not change DownValues[N].

So the question is: why function N[] behaves like that? Is it just some hard-coded rule, which is not described in terms of attributes, downvalues etc.?

$\endgroup$
4

1 Answer 1

14
$\begingroup$

Values of this type are actually stored in an analog to DownValues called NValues. Here's an example:

In[13]:= N[IndianaPi] = 4;
IndianaPi // NValues

Out[14]= {HoldPattern[
   N[IndianaPi, {MachinePrecision, MachinePrecision}]] :> 4}

As xzczd points out this is mostly a subset of what's mentioned here

Note that a similar mechanism is used for Format:

In[43]:= Format[IndianaPi] =
  Interpretation[I\[Pi], IndianaPi];
IndianaPi // FormatValues

Per bcp's comment, the Protected attribute need not be a problem because no assignment to N is actually ever done. For instance:

In[118]:= A /: HoldPattern@Set[A[q_], v_] := (q -> v);

In[119]:= Protect@A

Out[119]= {"A"}

In[120]:= A[1] = 2

Out[120]= 1 -> 2

That gives us no error. And yet:

In[121]:= Attributes@A

Out[121]= {Protected}
$\endgroup$
3
  • $\begingroup$ But the question was why N's Protected attribute does not forbid me to write N[***] = ***? $\endgroup$
    – bcp
    Commented Mar 14, 2017 at 8:56
  • 1
    $\begingroup$ I'll address that. We can do the same thing with UpValues. I don't know how it's implemented internally. $\endgroup$
    – b3m2a1
    Commented Mar 14, 2017 at 8:58
  • $\begingroup$ @bcp realized I didn't tag you so you probably didn't see that. $\endgroup$
    – b3m2a1
    Commented Mar 14, 2017 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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