# nth list element

Write a recursive function that accepts a list l and a number n and returns the nth element of l (0th element is leftmost).

\$ cat nle.rkt
#lang racket

(define (nth-list-element-generic f)

; Return a function accepting a list l and a whole number n
; that calls (f l n) to return the nth element of l (0th
; element is leftmost) if n is in the range [0..(length l));
; otherwise the function throws an exception.

(lambda (l n)
(if (and (<= 0 n) (< n (length l)))
(f l n)
(error (format
"the element index ~a is out of the range [0..~a)"
n (length l))))))

(define nth-list-element-recursive

(nth-list-element-generic
(lambda (l n)
(let loop ((l l) (n n))
(if (zero? n)
(car l)
(loop (cdr l) (- n 1)))))))

(define nth-list-element-iterative

(nth-list-element-generic
(lambda (l n)
(do ((l l (cdr l)) (n n (- n 1))) ((zero? n) (car l))
(void)))))

(require rackunit "utl.rkt")

(define (test-it f n)

(let

((l (vector->list (iota-vector n)))
(ce (lambda (l n)
(check-exn exn:fail? (lambda () (f l n))))))

(do ((i 0 (+ i 1))) ((= i n) (void))
(check-eq? (f l i) i))

(ce '() 0)
(ce l -1)
(ce l n)))

(test-it nth-list-element-recursive 10)
(test-it nth-list-element-iterative 10)

\$ racket nle.rkt

\$