1
$\begingroup$

Is there a way to print the argument of a function which results in a $RecursionLimit::reclim error?

As an example, cosider the code

fib[n_] := If[n == 1, 1, n*fib[n - 1]];
fib[5]
(* 120 *)
fib[1023]
(* $RecursionLimit::reclim: Recursion depth of 1024 exceeded. *)

the ideal output should be something like

120

Recursion error for n=1023

$RecursionLimit::reclim: Recursion depth of 1024 exceeded.

Any suggestions?

$\endgroup$
3
$\begingroup$

The function Check is what you are looking for.

fib[n_] := 
  Check[If[n == 1, 1, n*fib[n - 1]], Print["n = ", n]; Abort[]]

Block[{$RecursionLimit = 20}, fib[25]]

$RecursionLimit::reclim: Recursion depth of 20 exceeded. >>
n = 17

$Aborted
$\endgroup$
0
$\begingroup$

You also need to restrict the input to be a positive integer. Since you are basically defining the factorial function, I have renamed it to factorial rather than fib.

factorial::argv = 
  "The argument `1` is not a positive integer.";

factorial[n_] /; If[
   TrueQ[Element[n, Integers] && n > 0], True,
   Message[factorial::argv, n]; False] :=
 Check[If[n == 1, 1, n*fib[n - 1]],
  StringForm[
   "Recursion error for n = ``", n],
  $RecursionLimit::reclim]

factorial[-5]

factorial::argv: The argument -5 is not a positive integer.

factorial[-5]

factorial[5]

120

factorial[1023]

$RecursionLimit::reclim: Recursion depth of 1024 exceeded. >>

Recursion error for n = 1023

$\endgroup$
  • 2
    $\begingroup$ Well, "fib" need not stand for "Fibonacci" (maybe that was the point of it being a fib). $\endgroup$ – Daniel Lichtblau Jul 3 '14 at 15:25

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.