[Scheme] Checking The Validity of The Number Passed to The List

In many programming languages,
when we pass the number n to the array which the length is equal or less than n, we get an exception.

The following is the example of C:

int main(void){
    int hoge[] = {0,1,2,3};
    printf("%d", hoge[3]); // output: 3
    printf("%d", hoge[4]); // get a warning
    return 0;

We can implement this kind of exception in Scheme by using the procedure length which is introduced in SICP 2.2.1.

The code will be as follows:

; returns the length of a list
(define (length li)
  (define (length-iter n iter-li)
    (if (null? iter-li)
      (length-iter (+ n 1) (cdr iter-li))))
  (length-iter 0 li))

; check if the value passed to the list is valid
(define (cdr-chk-err li n)
  (cond ((or (> n (length li)) (= n (length li)))
    (error "Invalid value passed to the list. "))))

(define (list-ref n)
  (lambda (x)
    (cdr-chk-err x n)
    (if (= n 0)
      (car x)
      ((list-ref (- n 1)) (cdr x)))))

This works correctly.

(define l1 (list 1 2 3 4))
((list-ref 3) l1) ; returns 4
((list-ref 4) l1) ; error!




Leave a Reply