Exercises in this lecture  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'  Go to the slide, where this exercise belongs -- Keyboard shortcut: 'u'  

Exercise 1.12
The function butlast **

R5RS has functions such that list-ref and list-tail. (list-ref lst n) returns element number n in a list, (list-tail lst k) returns a suffix of list (omitting k elements). In this exercise we will program a function butlast. (butlast lst) returns all elements of lst apart from the last element. Thus, butlast computes the prefix of the list consisting of all elements but the last one. Needless to say, butlast assumes as a precondition that the input list is non-empty.

Let us notice that it is harder to compute the prefix of a list than a suffix of a list. Why?

The following implementation of butlast is tempting, but inefficient (quick and dirty):

  (define (butlast lst)
    (reverse (cdr (reverse lst)))))

Now, program butlast with a single traversal of the list.

Can you generalize butlast to compute the prefix of a list appart from the last n elements:

  (define (but-n-last lst n)

Please consider the similarity between but-n-last and list-prefix from one of the other exercises.