Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following function, albeit contrived:

Foo[x_Integer] :=
   i = 1;
   While[i <= x && i <= 10, i++];
   i - 1

I am looking for the following

Foo[1] = 1
Foo[10] = 10
Foo[11] = 10
Foo[Infinity] = 10

However Foo[Infinity] returns Foo[\[Infinity]] and not 10 .

Is there an something that I can do, short of: Foo[Infinity] = 10; to get Foo[Infinity] to return 10 ? The problem is i <= 10 is static in my contrived example, but will be dynamic in practice.

share|improve this question
up vote 16 down vote accepted

You can do this by using Alternatives to have the pattern accept either an integer or Infinity as an argument, like so:

Pillsy`Foo[x : (_Integer | Infinity)] :=
 Module[{limit = Min[x, 10], i = 1},
  While[i <= limit, ++i];
  i - 1]

It helps that Mathematica functions like Min and Max usually do the right thing with Infinity as an argument.

share|improve this answer

Your Answer


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.