S-99-18


S-99-18 Extract a slice from a list.

Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1.

Example:

 (slice '(a b c d e f g h i k) 3 7) 
 ; => (c d e f g) 

Solution:

 (define (take xs n) 
   (if (or (zero? n) (null? xs)) '() 
       (cons (car xs) (take (cdr xs) (- n 1))))) 
  
 (define (slice xs start end) 
   (cond ((null? xs) 
          '()) 
         ((> start 1) 
          (slice (cdr xs) (- start 1) (- end 1))) 
         (else 
          (take xs end))))