shorter list


Write recursive functions to 1) return a list's length and 2) return the shorter of two lists.

 $ cat sl.rkt 
 #lang racket 
  
  
 (define (length l) 
  
   ; Return the number of elements in the given list. 
    
   (let loop ((l l) (n 0)) 
     (if (null? l) 
       n 
       (loop (cdr l) (+ 1 n))))) 
  
  
 (define (shorter-list l1 l2) 
  
   ; Return the given lists in a pair, the car of which is no longer 
   ; than the cdr. 
  
   (let loop ((ls1 l1) (ls2 l2)) 
     (cond 
  
        ((null? ls1) 
          (cons l1 l2)) 
  
        ((null? ls2) 
          (cons l2 l1)) 
  
        (#t 
          (loop (cdr ls1) (cdr ls2)))))) 
  
  
 (require rackunit srfi/1) 
  
 (do ((i 0 (+ 1 i))) ((>= i 30) #t) 
   (let* ((n (random 10)) 
          (ln (length (make-list n)))) 
     (check-eq? ln n))) 
  
 (do ((i 0 (+ 1 i))) ((>= i 30) #t) 
   (let* ((l1 (make-list (random 10))) 
          (l2 (make-list (random 10))) 
          (p  (shorter-list l1 l2)) 
          (pa (car p)) 
          (pd (cdr p))) 
  
     (check-true (<= (length pa) (length pd))) 
     (check-true (or (eq? l1 pa) (eq? l1 pd))) 
     (check-true (or (eq? l2 pa) (eq? l2 pd))) 
     (check-false (eq? pa pd)))) 
  
  
  
 $ racket sl.rkt 
 #t 
 #t 
  
 $