Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
The function butlast


Here is an implementation of butlast and but-n-last:

(define (butlast lst)
  (cond ((null? lst)
           (error "Cannot apply butlast on an empty list"))
        ((null? (cdr lst))  ; a list of a single element
           '())
        (else (cons (car lst) (butlast (cdr lst))))))

(define (but-n-last lst n)
  (cond ((< (length lst) n)
           (error "The list is too short for but-n-last"))
        ((= (length lst) n)
           '())
        (else (cons (car lst) (but-n-last (cdr lst) n)))))