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

Exercise solution:
Every second element of a list


;; Return every second element of list, starting with the first element.
(define (every-second-element lst)
  (cond ((null? lst) '())
        ((null? (cdr lst)) (list (car lst)))
        (else (cons (car lst) (every-second-element (cddr lst))))))

; Return every n-th element of lst. Assume as a pre-condition that n >= 1.
(define (every-nth-element n lst)
  (if (shorter-than? n lst)
      (list (car lst))
      (cons (car lst) (every-nth-element n (list-tail lst n)))))

; Expensive variant.
(define (shorter-than? n lst)
  (< (length lst) n))

; Does lst have n elements, or fewer?
(define (shorter-than? n lst)
  (or (and (null? lst) (>= n 0))
      (and (not (null? lst)) (shorter-than? (- n 1) (cdr lst)))))

; An alternative with cond
(define (shorter-than? n lst)
  (cond ((null? lst) (>= n 0))
        ((not (null? lst)) (shorter-than? (- n 1) (cdr lst)))))

; Return every n-th element of lst. Assume as a pre-condition that n >= 1.
(define (every-nth-element n lst)
  (cond ((null? lst) '())
        ((shorter-than? n lst) (list (car lst)))
        (else (cons (car lst) (every-nth-element n (list-tail lst n))))))

(define (every-second-element lst)
  (every-nth-element 2 lst))

; Does not work - calls for currying.
; (define every-second-element (every-nth-element 2))

The function every-second-element is useful to extract the keys or values of a property list.