Search code examples
schemeracketr5rs

SCHEME Mutable Functions


I've been self-teaching myself Scheme R5RS for the past few months and have just started learning about mutable functions. I've did a couple of functions like this, but seem to find my mistake for this one.

(define (lst-functions)
  (let ((lst '()))
    (define (sum lst)     
      (cond ((null? lst) 0)
            (else
             (+ (car lst) (sum (cdr lst))))))
    (define (length? lst)
      (cond ((null? lst) 0)
            (else
             (+ 1 (length? (cdr lst))))))
    (define (average)
      (/ (sum lst) (length? lst)))
    (define (insert x)
      (set! lst (cons x lst)))
    (lambda (function)
      (cond ((eq? function 'sum) sum)
            ((eq? function 'length) length?)
            ((eq? function 'average) average)
            ((eq? function 'insert) insert)
            (else
             'undefined)))))

(define func (lst-functions))
((func 'insert) 2)
((func 'average))

Solution

  • You're not declaring the lst parameter in the procedures that use it, but you're passing it when invoking them. I marked the lines that were modified, try this:

    (define (lst-functions)
      (let ((lst '()))
        (define (sum lst)     ; modified
          (cond ((null? lst) 0)
                (else
                 (+ (car lst) (sum (cdr lst))))))
        (define (length? lst) ; modified
          (cond ((null? lst) 0)
                (else
                 (+ 1 (length? (cdr lst))))))
        (define (average)
          (/ (sum lst) (length? lst)))
        (define (insert x)
          (set! lst (cons x lst)))
        (lambda (function)
          (cond ((eq? function 'sum) (lambda () (sum lst)))        ; modified
                ((eq? function 'length) (lambda () (length? lst))) ; modified
                ((eq? function 'average) average)
                ((eq? function 'insert) insert)
                (else
                 'undefined)))))
    

    Now it works as expected:

    (define func (lst-functions))
    ((func 'insert) 2)
    
    ((func 'average)) 
    => 2
    ((func 'sum))
    => 2
    ((func 'length))
    => 1