racket Recursion Using rec


Example

#lang racket
(require mzlib/etc)
((rec sum-of-list
   (λ (l)
     (if (null? l)
         0
         (+ (car l) (sum-of-list (cdr l))))))
 '(1 2 3 4 5))
;; => 15

;; Outside of the rec form, sum-of-list gives an error:
;; sum-of-list: undefined;
;;  cannot reference an identifier before its definition

This is similar to define, but the sum-of-list identifier is not visible outside of the rec form.

To avoid using an explicit λ, it is possible to replace sum-of-list with (sum-of-list args ...):

#lang racket
(require mzlib/etc)
((rec (sum-of-list l)
   (if (null? l)
       0
       (+ (car l) (sum-of-list (cdr l)))))
 '(1 2 3 4 5))
;; => 15