When you write
f[1] = 5;
f[x_] := x
you are specifying how expressions will be rewritten during evaluation. f[1]
is just a pattern: any expression that matches that pattern will be rewritten as 5
. The 'Blank' pattern represents anything else, so:
f[y]
(* y *)
The possibility that y
might take the value 1
at some later stage of the computation isn't taken into account.
One the other hand:
g[x_] := Piecewise[{{5, x == 1}}, x^2]
g[y]
(* Piecewise[{{5, y == 1}}, y^2] *)
This treats y
properly as a variable.
Note that symbolic mathematics in Mathamatica can "reason" about Piecewise
expressions, but cannot do so with collections of rewriting rules, so f
is not a suitable function to feed to symbolic methods.
If[]
statement orWhich[]
They are different. The first method uses two patterns. There are several benefits/pitfalls, but that requires much explaining. $\endgroup$f[x_]:=Which[x==1,5,True,x^2]
$\endgroup$