Scheme: what are the benefits of letrec?
- by Ixmatus
While reading "The Seasoned Schemer" I've begun to learn about letrec. I understand what it does (can be duplicated with a Y-Combinator) but the book is using it in lieu of recurring on the already defined function operating on arguments that remain static.
An example of an old function using the defined function recurring on itself (nothing special):
(define (substitute new old lat)
(cond
((null? l) '())
((eq? (car l) old)
(cons new (substitute new old (cdr l))))
(else
(cons (car l) (substitute new old (cdr l))))))
Now for an example of that same function but using letrec:
(define (substitute new old lat)
(letrec
((replace
(lambda (l)
(cond
((null? l) '())
((eq? (car l) old)
(cons new (replace (cdr l))))
(else
(cons (car l) (replace (cdr l))))))))
(replace lat)))
Aside from being slightly longer and more difficult to read I don't know why they are rewriting functions in the book to use letrec. Is there a speed enhancement when recurring over a static variable this way because you don't keep passing it??
Is this standard practice for functions with arguments that remain static but one argument that is reduced (such as recurring down the elements of a list)?
Some input from more experienced Schemers/LISPers would help!