Batch Script Recursive Functions
Recursive Functions
The ability to completely encapsulate the body of a function, keeping changes to variables local to the function and invisible to the caller, is critical to implementing recursive functions in batch script.
Example
The following example shows how recursive functions can be used.
The example shows how to compute a Fibonacci number recursively. The recursion stops when the Fibonacci algorithm reaches a number greater than or equal to a given input number. The example starts with the numbers 0 and 1, the :fibo
function recursively calls to calculate the next Fibonacci number until it finds the Fibonacci number greater than or equal to 1000000000.
The first argument of the fibo
function is the name of the variable to store the output in. This variable must be initialized to the Fibonacci number to start with and will be used as current Fibonacci number when calling the function and will be set to the subsequent Fibonacci number when the function returns.
@echo off
set "fst=0"
set "fib=1"
set "limit=1000000000"
call:fibo fib,%fst%,%limit%
echo.The next Fibonacci number greater or equal %limit% is %fib%.
echo.&pause&goto:eof
:: Function starts below here
:fibo -- calculate recursively the next Fibonacci number greater or equal to a limit
:: -- %~1: return variable reference and current Fibonacci number
:: -- %~2: previous value
:: -- %~3: limit
SETLOCAL
set /a "Number1=%~1"
set /a "Number2=%~2"
set /a "Limit=%~3"
set /a "NumberN=Number1 + Number2"
if /i %NumberN% LSS %Limit% call:fibo NumberN,%Number1%,%Limit%
(ENDLOCAL
IF "%~1" NEQ "" SET "%~1=%NumberN%"
)
goto:eof
The next Fibonacci number greater or equal 1000000000 is 1134903170.