9
$\begingroup$

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.

$\endgroup$
16
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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