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 have the following function, albeit contrived:

Foo[x_Integer] :=
  Module[{i},
   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

1 Answer 1

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

 
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.