Message Boards Message Boards

[✓] Provide a default value for x in f[x_?NumericQ]:=...?

GROUPS:

If the restriction for x is expressed by specifying the Head, there is no problem: e.g. f[x_Complex : 1+ I] := .... . If the restriction is expressed by a predicate I did not find a way to set a default value for the argument. Who can help?

POSTED BY: Ulrich Mutze
Answer
2 months ago

In this case, you will want the expanded form of Pattern[] to account for both PatternTest[] and Optional[]. Thus:

f[x : (_?NumericQ) : Pi] := Sin[x]

{f[], f[Pi/2], f[y]}
   {0, 1, f[y]}
POSTED BY: J. M.
Answer
2 months ago

Great help! Thanks a lot

POSTED BY: Ulrich Mutze
Answer
2 months ago

That's another combination of features — a predicate pattern for a function argument along with a default value for that argument — that does not seem to be covered in the Documentation Center.

I recall that it gave me considerable trouble when I first encountered the situation myself.

It's the sort of thing that, so far as I have been able to find, is dearly missing from the Documentation Center. (One of many "putting things together" issues.)

POSTED BY: Murray Eisenberg
Answer
2 months ago

Armed with J.M.'s insights I started a walk through the Wolfram documentation system and found that all you need to know about the problem at hand is really there. Nevertheless, your remarks are very true. Why the solution to such a standard problem is hidden so carefully? In the given case the kindness of the community (J.M. in particular) overcompensated this shortcoming.

POSTED BY: Ulrich Mutze
Answer
2 months ago

One thing to pay attention to when doing this is to make sure that the default value matches the pattern.

What happens if it doesn't match has even changed between versions (rather arbitrarily, and without documentation or warning):

https://mathematica.stackexchange.com/questions/108636/version-inconsistency-with-optional-arguments-what-if-the-default-value-doesnt

POSTED BY: Szabolcs Horvát
Answer
2 months ago

Group Abstract Group Abstract