Hacker News new | ask | show | jobs
by chisophugis 4378 days ago
Here's a couple elementary examples that are useful:

f[x_Integer]:=x^2

Basically the pattern for the argument of f must match the pattern _Integer, which means that the argument is an integer. If the pattern does not match, then it stays in an unevaluated form; you could have it throw an error by having an extra pattern f[_]:=Assert[False] or whatever.

f[x_] /; x>2 := x^2

Same, but in this case only if x>2.

Basic symbolic manipulation:

Sin[x^2 + x + 2] /. x->3

Evaluate at x=3.

θ^2/r /. {r -> Sqrt[x^2 + y^2], θ -> ArcTan[x, y]}

Convert from polar coordinates to Cartesian.

General programming:

In[21]:= Cases[{1,2,3,4}, x_ /; x>2 && PrimeQ[x] -> x^2] Out[21]= {9}

Kind of like a list comprehension.