Reverse string: recursion in RimStone


This example will reverse a string, i.e. turn it around so that it's like in the mirror. This will be done by using recursion; of course it can be done in other ways too, but this will demonstrate the use of recursion to manipulate a string. For a different recursion example (that calculates a factorial of a number), see article-recursion-factorial.

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

This will create the file "rev.rim", which contains two handlers, one which is public (and that's the one we'll call) and the other, recursive one:
cat << 'EOF' > rev.rim
%% /rev/string get-param str type string, str_beg type number, str_end type number
    if-true str_beg lesser-than str_end
        set-number end = str[str_end]
        set-string str[str_end] = str[str_beg]
        set-string str[str_beg] = end
        call-handler "/rev/string" set-param str, str_beg=str_beg+1, str_end=str_end-1
    end-if
%%

%% /rev public
    set-string str="This is some string to reverse"
    string-length str to str_len
    call-handler "/rev/string" set-param str, str_beg=0, str_end=str_len-1 get-param str type string
    print-out str new-line
%%
EOF

The "/rev/string" handler takes in the string itself (which is changed, but if you don't want that make a copy of it first in "/rev" caller handler), and also the index of the first character to reverse and the index of the last one. The index starts with 0 (the first byte), and ends with the length of the string minus 1 (i.e. the same indexing scheme as in most other languages).

The code itself is pretty self-explanatory: the first and last character are swapped, then the "/rev/string" handler is called again but this time with the substring whic starts one byte after the character we swapped, and ends one byte before the other swapping character. This is repeated until the beginning is equal or greater than the ending.

Make the application:
rim -q

Test it (we will reverse the string "This is some string to reverse"):
rim -r --req="/rev" --exec --silent-header

As expected, the result is a reversion of this string:
esrever ot gnirts emos si sihT



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