Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function types declarations in Mathematica

I have bumped into this problem several times on the type of input data declarations mathematica understands for functions.

It Seems Mathematica understands the following types declarations: _Integer, _List, _?MatrixQ, _?VectorQ

However: _Real,_Complex declarations for instance cause the function sometimes not to compute. Any idea why?

What's the general rule here?

like image 439
Phil Avatar asked Nov 30 '22 08:11

Phil


1 Answers

When you do something like f[x_]:=Sin[x], what you are doing is defining a pattern replacement rule. If you instead say f[x_smth]:=5 (if you try both, do Clear[f] before the second example), you are really saying "wherever you see f[x], check if the head of x is smth and, if it is, replace by 5". Try, for instance,

Clear[f]
f[x_smth]:=5
f[5]
f[smth[5]]

So, to answer your question, the rule is that in f[x_hd]:=1;, hd can be anything and is matched to the head of x.

One can also have more complicated definitions, such as f[x_] := Sin[x] /; x > 12, which will match if x>12 (of course this can be made arbitrarily complicated).

Edit: I forgot about the Real part. You can certainly define Clear[f];f[x_Real]=Sin[x] and it works for eg f[12.]. But you have to keep in mind that, while Head[12.] is Real, Head[12] is Integer, so that your definition won't match.

like image 177
acl Avatar answered Dec 04 '22 02:12

acl