How to define a function in Mathematica without overriding the previous definition?

I'm a beginner at Mathematica and trying to define a function for the Collatz conjecture, and here is my code:

g[n_] := g[n] = n/2 /; EvenQ[n];
g[n_] := g[n] = 3 n + 1 /; OddQ[n];


And I find that the definition for Odd n's would override the former definition,?g gives only

g[n_] := g[n] = 3 n + 1 /; OddQ[n]


However, a definition like the following one will not be overriding the other definition:

f[x_] := x /; x > 0;
f[x_] := -x /; x <= 0


Why is this the case and how should I fix this?

\$Version

(* "13.0.1 for Mac OS X x86 (64-bit) (January 28, 2022)" *)

Clear["Global*"]

g[n_ /; EvenQ[n]] := g[n] = n/2;
g[n_ /; OddQ[n]] := g[n] = 3 n + 1;

g /@ Range[5]

(* {4, 1, 10, 2, 16} *)

?? g


EDIT: The position affects the order of evaluation, i.e., which part of the expression the condition is associated with. If you want to place the condition at the end, use parentheses to control the order of evaluation, i.e.,

Clear["Global*"]

g[n_] := (g[n] = n/2) /; EvenQ[n];
g[n_] := (g[n] = 3 n + 1) /; OddQ[n];

g /@ Range[5]

(* {4, 1, 10, 2, 16} *)

?? g


• Thank you, does that mean the position of condition /; matters? What's the difference between the condition in brackets and condition at the end of statement? Mar 17, 2022 at 14:08

You may use PatternTest in the function signature or use Piecewise in the function body.

With PatternTest.

ClearAll[g]
g[n_?EvenQ] := g[n] = n/2
g[n_?OddQ] := g[n] = 3 n + 1


then

g /@ Range@5

{4, 1, 10, 2, 16}


With Piecewise.

ClearAll[h]
h[n_] := h[n] =
Piecewise[{
{n/2, EvenQ[n]}
, {3 n + 1, OddQ[n]}
}]


then

h /@ Range@5

{4, 1, 10, 2, 16}


Hope this helps.