Coyote's Guide to IDL Programming

Writing a Recursive Function

QUESTION: Can I write a recursive function in IDL?

ANSWER: Yes. The only trick is to be sure to include the FORWARD_FUNCTION command inside the recursive function code before the function is called recursively. This will prevent IDL from interpreting the function call inside the code as a variable reference.

A famous recursive function is the one that calculates the factorial value of the number N. For example, N * (N-1) * (N-2) * ... * 1. Here is how you write that recursive function in IDL. (Click here to download the example IDL code.)

   FUNCTION FACTORIAL, number
   FORWARD_FUNCTION FACTORIAL
   IF number LE 1 THEN RETURN, 1L
   RETURN, LONG(number) * FACTORIAL(number - 1)
   END

You can run the program by typing something like this:

   IDL> PRINT, FACTORIAL(5)
     120

Google
 
Web Coyote's Guide to IDL Programming