This question already has an answer here:

I have been met with the following problem:

I have defined the following:


That means, if I call:


The output of the program is going to be simply:


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_goldberg Dec 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.

  • $\begingroup$ p.s. also related: 45351 $\endgroup$ – Kuba Dec 1 '15 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] *)
(* 289 *)
  • $\begingroup$ For your definition myFunc[-1] doesn't return myFunc[0], but maybe I'm misreading the question. $\endgroup$ – Karsten 7. Dec 1 '15 at 16:23
  • $\begingroup$ 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. $\endgroup$ – Jason B. Dec 1 '15 at 16:26
  • $\begingroup$ @Guest245 Please clarify if you really mean "If e <= 0, output myFunc[0]" or if you mean "If e <= 0, output myFunc[e]". $\endgroup$ – 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]]

Not the answer you're looking for? Browse other questions tagged or ask your own question.