REBOL 3.0

Closure Functions

Carl Sassenrath, CTO
REBOL Technologies
24-Apr-2006 16:32 GMT

Article #0012
Main page || Index || Prior Article [0011] || Next Article [0013] || 10 Comments || Send feedback

Closure functions will be provided as a standard part of REBOL 3.0.

The concept of function closures is nothing new (30 years at least), and can be found in most types of functional languages. A closure is a special type of, or characteristic of, a function that keeps the local environment (arguments and local variables) of the function "alive", even after the function has returned.

 Advantages:The environment of the function (words and data) remains valid after the function returns (which is not true of normal functions). This is useful if you want to return words or other data from the function, and you want to still access the values of the words.
 Disadvantages:They evaluate slower than normal functions because they are allocated and bound at run time. Also, closures often require more memory (and cause more recycling), depending on how you use and store their results.

In REBOL 3.0, closure functions are implemented with the closure! datatype and a new mezzanine function called closure. Here is an example that defines a new closure function called hash-name:

hash-name: closure [name [string!] /local hash] [
    hash: checksum/secure name
    return [name hash]  ; note: returns words, not values
]

When a closure is defined a REBOL object is created and the function body is bound to that object. When the function is evaluated, the original function object is cloned and the body is deep copied and rebound to the newly cloned object.

You call closure functions in the same way as you would any function:

result: hash-name "Bob"
print second result

You can test for a closure function with:

if closure? :hash-name [print "It is true"]

and, this expression is also true:

if any-function? :hash-name [print "It is true"]

To read more about the concept of closures, see Function Closure in the Wikipedia, and also Ladislav Mecir provides useful methods and examples of REBOL closures (that work in current versions of REBOL) in his "Bind A Function Yourself" tutorials and code.

10 Comments

REBOL 3.0
Updated 21-Nov-2017 - Edit - Copyright REBOL Technologies - REBOL.net