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.

I want to define a function f with an argument that matches only when an argument Head is NOT of a given value.

I know I can define a pattern that matches the Head for an argument:

f[a_Integer] := 2 a

Now, how do I define a version that matches only when argument a is NOT an Integer?

f[a_NotAnInteger] := <something else>
share|improve this question
4  
can't you just do f[a_Integer] := 2 a; f[a_] := 2000 a ? –  Nasser Nov 2 '13 at 20:26
add comment

2 Answers 2

up vote 16 down vote accepted

You need Except:

f[a : Except[_Integer]] := 2 a

In addition to being concise, this has an advantage that you can use it in functions which hold their arguments, and don't need to worry about evaluation leaks, since this test is done entirely by the pattern-matcher. For this reason, this is also more efficient than testing head explicitly.

share|improve this answer
add comment

Leonid's answer is the best I think, but Nasser's method in a comment is also valid. It is based on the precedence of rules. If you define a behavior for the Head you don't want you can use a fall-through definition for everything else, e.g.:

f[a_Integer] := 2 a
f[a_] := {1, 2, 3}^a

f /@ {4, 3.14, 3/5}
{8, {1, 8.81524, 31.4891}, {1, 2^(3/5), 3^(3/5)}}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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