Rebol Programming/Language Features/Recursion

Recursion edit

Rebol allows for recursive programming. This is when a function is able to invoke itself, and can be quite useful eg. for tracing through a tree structure such as spidering a website. However, if the number of times the function is invoked is too many, a stack error occurs. It is better to restrict the use of recursive functions to where the recursion is known to be limited.

However, it should be noted that the Rebol interpreter evaluates Rebol code in a recursive fashion.

For example of a recursive function, here we define read-dir to collect file and directory names from the directory given to it as an argument, and all the sub directories below that directory.

file-list: []
read-dir: func [ 
   dir [file!]
][
   foreach file read dir [
       file: either dir = %./ [file][dir/:file]
       append file-list file
           if dir? file [
           	read-dir file
           ]
    ]
]
read-dir %./
new-line/all file-list on
print mold file-list

Starting with an empty file-list block, the function read-dir reads all the files in the current directory. If the file is a directory, it then calls itself to read that directory, returning to the calling version of itself on completion.

The question is often asked as to whether Rebol supports Tail recursion, and Continuations. The answer is, that it used to do so, but it was removed as it caused Rebol to consume large amounts of memory. Carl Sassenrath, Rebol's chief architect, has stated that at some stage tail recursion may be re-implemented, but it is not a priority. However, tail recursion would fix the problems sometimes seen with a stack overflow with the parse dialect, and allow deeply recursive functions.

Examples edit

  • wikichanges.r An example on crawling the Rebol Programming wikibook to see the latest changes