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

This question already has an answer here:

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.

## marked as duplicate by Kuba♦, user9660, dr.blochwave, MarcoB, m_goldbergDec 1 '15 at 16:17

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

• p.s. also related: 45351 – Kuba Dec 1 '15 at 13:47

## 2 Answers

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. – Karsten 7. Dec 1 '15 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. – Jason B. Dec 1 '15 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]". – Karsten 7. Dec 1 '15 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]]