Sean Eshbaugh

Web Developer + Programmer

Nth Element of a List in Scheme

Common Lisp and Clojure both provide a built-in nth function for retrieving the nth element in a list. Surprisingly enough Scheme (MIT Scheme at least) doesn't that I'm aware of.

Fortunately nth is super simple to implement in a recursive fashion:

(define (nth n l)
  (if (or (> n (length l)) (< n 0))
    (error "Index out of bounds.")
    (if (eq? n 0)
      (car l)
      (nth (- n 1) (cdr l)))))

After checking to make sure that the index n isn't greater than the length of the list l or less than 0 the function checks to see if n is 0. If it is then it simply returns the first item in l with car. Otherwise nth is called again with n - 1 and the tail of l, retrieved with cdr.

seshbaugh ~% scheme --load nth.scm
;Loading "nth.scm"... done

1 ]=> (nth 3 '(1 2 3 4 5))

;Value: 4

I'm reasonably certain that this function is tail recursive; so it should work just fine, albeit slowly, for very long lists.