Message Boards Message Boards

1
|
6569 Views
|
5 Replies
|
10 Total Likes
View groups...
Share
Share this post:

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

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
5 Replies

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
Posted 7 years 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.

Great help! Thanks a lot

POSTED BY: Ulrich Mutze

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

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
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract