# Deciding whether the return value of a function is defined based on its input [duplicate]

I have been met with the following problem:

I have defined the following:

myFunc[e_Integer];


That means, if I call:

myFunc[0]


The output of the program is going to be simply:

myFunc[0]


Now, I would like to do the following:

If e > 0, do something. If e <= 0, output myFunc[0], just like in the previous example. How would I go about doing this?

I was thinking about something like this, but I have no idea what to put in the last argument of the If function.

myFunc[e_Integer] := If[e>0, e*e , (* ? *) ];


Any responses would be greatly welcome.

• p.s. also related: 45351
– Kuba
Commented Dec 1, 2015 at 13:47

When you type e_ or e_Integer you are using a pattern. You can put constraints on the pattern as well using the ;/ operator

myFunc[e_Integer /; e > 0] := e*e
myFunc[0]
myFunc[17]
(* myFunc[0] *)
(* 289 *)

• For your definition myFunc[-1] doesn't return myFunc[0], but maybe I'm misreading the question. Commented Dec 1, 2015 at 16:23
• I read the question that he wanted it to return e^2 if it were positive, but to behave the same way as before if it were negative. He did write it ambiguously. Commented Dec 1, 2015 at 16:26
• @Guest245 Please clarify if you really mean "If e <= 0, output myFunc[0]" or if you mean "If e <= 0, output myFunc[e]". Commented Dec 1, 2015 at 16:34

Here are three ways to get it working using If in the definition of the function.

1) Using Defer

myFunc[e_Integer] := If[e > 0, e*e, Defer @ myFunc[0]]


2) Using HoldForm

myFunc[e_Integer] := If[e > 0, e*e, HoldForm @ myFunc[0]]


3) Using Inactivate

myFunc[e_Integer] := If[e > 0, e*e, Inactivate @ myFunc[0]]