Recursive Bindings in Chez Scheme

rec语法是Chez Scheme中一个非常有用的扩展,在不依赖外部变量进行递归时将很有用,可以减轻代码且使代码更加容易阅读。


这是语法描述: (rec var expr) syntax returns: value of expr libraries: (chezscheme)

The syntactic form rec creates a recursive object from expr by establishing a binding of var within expr to the value of expr. In essence, it is a special case of letrec for self-recursive objects.

This form is useful for creating recursive objects (especially procedures) that do not depend on external variables for the recursion, which are sometimes undesirable because the exter-nal bindings can change. For example, a recursive procedure defined at top level depends on the value of the top-level variable given as its name. If the value of this variable should change, the meaning of the procedure itself would change. If the procedure is defined instead with rec, its meaning is independent of the variable to which it is bound.

简要翻译一下: 语法rec 通过在expr中建立var与expr的值的绑定,创建一个递归对象。从本质上讲,这是letrec用于自递归对象的一种特殊情况。

语法rec通过绑定expr中创建一个递归对象,用来 这种形式对于创建不依赖于外部变量进行递归的递归对象(尤其是过程)很有用,因为外部绑定可能会发生变化,所以有时这是不可取的。


看一个例子来感受一下: 给定一个全是数字的list,对于每一个数字n,算出$1+2+…+n$的和,最终返回和的list.

(map (rec sum
       (lambda (x)
		   (if (= x 0) 0
			   (+ x (sum (- x 1)))))) (0 1 2 3 4 5))  (0 1 3 6 10 15)

如果没有rec语法,用letrec也是可以的,但是稍显麻烦,代码也多一些,所以rec还是很好用的


最后看一下rec语法的定义:

(define-syntax rec
  (syntax-rules ()
    [(_ x e) (letrec ((x e)) x)]))