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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With