Hi IML enthusiasts!
Well this is a question that came to my mind as I was refreshing my IMLPlus knowledge last week. I tried to write a simple recursive module, but I couldn't make it work. To my surprise, I discovered in the IML documentation that it is not permitted to defines modules that call themselves. That is, if you define and execute a module such as:
*Factorial using recursive IML module;
start fact(n);
if n=1 then return 1;
else return n*fact(n-1);
finish;
x=fact(3);
You will get this error message:
»ERROR: Module FACT called again before exit from prior call.
ERROR: An error occurred while executing module "fact". (25, 7)
An error in the program occurred on the SAS server. (+3, 20)
I tried the following recursive implementation using macros. It is not very user-friendly, but it works:
*1) Defining a recursive factorial using macros;
submit;
%macro fact(n);
%if &n=1 %then 1;
%else %eval(&n*%fact(%eval(&n-1)));
%mend fact;
endsubmit;
*2) Calling macro and retrieving results using SYMPUT, SYMGET...;
results = J(10,2,'@@@@@@@@');
mattrib results colname={"n" "factorial(n)"};
do n=1 to 10;
call symput("n",char(n));
@%let fact_n = %fact(&n);
results[n,1] = char(n,2);
results[n,2] = symget("fact_n");
end;
print results;
However, the factorial is a toy problem and I don't know if the same procedure would apply to more elaborated functions. I couldn't make the Fibonacci works, not to mention e.g. the Ackermann function. I am pretty sure there may be more elegant alternatives to write recursive functions within IML/IMLPlus. What do you think?
Best regards,