How to Combine Pattern Constraints and Default Values for Function Arguments?

Perhaps this?

foo[x : (_?IntegerQ) : 1] := x;

foo[]
foo[7]
foo["string"]
1
7
foo["string"]

Update: since version 10.1 one does not need to explicitly include the default in the pattern as described below; see:

  • Version inconsistency with optional arguments: what if the default value doesn't match the pattern?

As Leonid reminds, if the default value does not match the test function it will not be returned. To allow for this you can explicitly include the value in the pattern:

ClearAll[foo]
foo[x : (_?IntegerQ | "default") : "default"] := x;

foo[]
foo[7]
foo["string"]
"default"
7
foo["string"]

In the comments magma makes an excellent point. You can use multi-clicking, or as I prefer Ctrl+. to examine parsing. See this answer.


As a complement, you can also use:

Clear[foo]
foo[n:_Integer?Positive:1]:=n

That filters the foo function argument according to a Positive predicate and an Integer Head and provides in the same time a default value=1.

Examples

foo[2]

foo[2.0]

foo[]

foo[-1]

prints:

2

foo[2.]

1

foo[-1]