Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

I would like to create a function that acts on whether the input is even or odd, e.g.:

In[644]:= f[a_] = If[EvenQ[a], 2 a, 3 a];
          f[2]

Out[645]= 6

I've determined (I think) that this is because a is an expression and QEven returns false for expressions. How do I hold off evalution of this until input is given? I thought something like Defer would work but then it is never evaluated (see below)!

In[641]:= g[a_] = If[Defer[EvenQ[a]], 2 a, 3 a]

Out[641]= If[EvenQ[a], 2 a, 3 a]

In[643]:= g[3]

Out[643]= If[EvenQ[3], 2 * 3, 3 * 3]

Apologies if this gets asked a lot - I assume this is a common issue, but I was unable to come up with appropriate search terms to describe it (I'm not very familiar with Mathematica terminology yet). Thanks!

share|improve this question

marked as duplicate by Kuba, Artes, Leonid Shifrin, Sjoerd C. de Vries, Yves Klett Oct 25 '13 at 14:34

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.

1  
You need to SetDelayed instead of Set. f[a_] := ... –  Kuba Oct 25 '13 at 10:36
    
Brilliant thanks, that thread looks very useful. It should have been my first port of call! –  Hemmer Oct 25 '13 at 10:39

1 Answer 1

fun[x_?EvenQ] := 2 x
fun[x_?OddQ] := 3 x

Non-integer arguments will just return the fun[arg].

fun[2] yields 4 and fun[3] yields 9.

share|improve this answer

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