2
$\begingroup$

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.

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

2 Answers 2

0
$\begingroup$

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 *)
$\endgroup$
3
  • $\begingroup$ For your definition myFunc[-1] doesn't return myFunc[0], but maybe I'm misreading the question. $\endgroup$
    – Karsten7
    Commented Dec 1, 2015 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.
    Commented Dec 1, 2015 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$
    – Karsten7
    Commented Dec 1, 2015 at 16:34
0
$\begingroup$

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]]
$\endgroup$

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