Calculate factorial: recursion in RimStone


Computing factorial is commonly used to demonstrate recursion in a programming language, and this example will do that. For a recursion example that manipulates a string, see article-recursion-reverse-string.

First, create a directory, and an application "recursive":
mkdir -p recsv
cd recsv
rim -k recursive

This will create the code to compute a factorial:
cat << 'EOF' > fact.rim
%% /fact/compute get-param n type number, result type number
    if-true n greater-equal 1
        call-handler "/fact/compute" set-param n=n-1, result=result*n
    end-if
%%

%% /fact public
    call-handler "/fact/compute" set-param n=10, result=1 get-param result type number
    print-out "Factorial is ", result new-line
%%
EOF

The handler "/fact/compute" calculates the factorial of number "n", and stores the result in "result". It is called from the handler "/fact", and the parameter "result" is both an input and output parameter in this example. "/fact/compute" will calculate a factorial by multiplying the input number with the one lesser by 1, and continuing until the lesser number is 1.

Make the application:
rim -q

Execute the code (we specified to calculate the factorial of 10):
rim -r --req="/fact" --exec --silent-header

The result as expected is:
Factorial is 3628800



Copyright (c) 2019-2025 Gliim LLC. All contents on this web site is "AS IS" without warranties or guarantees of any kind.