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$ 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$ Commented Mar 14, 2017 at 8:58
  • $\begingroup$ @bcp realized I didn't tag you so you probably didn't see that. $\endgroup$ Commented Mar 14, 2017 at 9:10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.