Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Default behave like this?

One may set a Default value for the arguments of a function:

Default[f] = 5;

And then use:

f[a_, b_.] := {a, b}

f[1, 2]
f[1]
   {1, 2}
   {1, 5}

This creates the following Values:

DefaultValues[f]
DownValues[f]
   {HoldPattern[Default[f]] :> 5}
   {HoldPattern[f[a_, b_.]] :> {a, b}}

From this one might think that the value 5 is not fixed in the definition of f, but addresses the DefaultValues assignment. However, if we change the DefaultValues, either directly or using:

Default[f] = 9;

DefaultValues[f]
   {HoldPattern[Default[f]] :> 9}

and use f again:

f[1]
   {1, 5}

we see that the new value is not used.

Therefore, my questions are:

  • Why does the default value used by f[a_, b_.] := {a, b} not change with DefaultValues?

  • Where is the real default value (5) stored, since it does not appear in either DownValues or DefaultValues?

like image 432
Mr.Wizard Avatar asked Jun 14 '11 00:06

Mr.Wizard


People also ask

What does it mean when someone has a default?

A default occurs when a borrower stops making the required payments on a debt. Defaults can occur on secured debt, such as a mortgage loan secured by a house, or unsecured debt, such as credit cards or a student loan. Defaults expose borrowers to legal claims and may limit their future access to credit.

How will a default affect me?

A default will appear on your credit file for six years, even if you pay off the debt in full. This means it'll be harder to get credit cards, loans or bank accounts because the default tells the creditor there's a greater risk of you not paying.


1 Answers

Not an answer, but:
Using the behaviour that the original default is kept until the function is redefined suggests a quick work-around:

Define a global variable for the Default before any other definitions are made.

In[1]:= Default[f]:=$f
In[2]:= f[a_.]:=a

In[3]:= f[]
Out[3]= $f

In[4]:= $f=5; f[]
Out[5]= 5
In[6]:= $f=6; f[]
Out[7]= 6
In[8]:= $f=.; f[]
Out[9]= $f

This also works for Optional

In[1]:= g[a_:$g] := a

In[2]:= g[]
Out[2]= $g

In[3]:= $g=1; g[]
Out[4]= 1
like image 55
Simon Avatar answered Oct 10 '22 04:10

Simon