2

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.

Kuba
  • 136,707
  • 13
  • 279
  • 740
Guest245
  • 21
  • 1

2 Answers2

0

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 *)
Jason B.
  • 68,381
  • 3
  • 139
  • 286
  • For your definition myFunc[-1] doesn't return myFunc[0], but maybe I'm misreading the question. – Karsten7 Dec 01 '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 01 '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]". – Karsten7 Dec 01 '15 at 16:34
0

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]]
Karsten7
  • 27,448
  • 5
  • 73
  • 134