s-99-15


S-99-15 Replicate the elements of a list a given number of times.

Example:

 (repli '(a b c) 3) 
 ; => (a a a b b b c c c) 

Solution:

With the help of the function repeat:

 (define (repeat x n) 
   (if (zero? n) '() 
       (cons x (repeat x (- n 1))))) 
  
 (define (repli xs n) 
   (if (null? xs) '() 
       (append (repeat (car xs) n) (repli (cdr xs) n)))) 

Or else in one go:

 (define (repli xs n) 
   (if (null? xs) '() 
       (let loop ((i (- n 1)) (x (car xs))) 
         (if (zero? i) 
             (cons x (repli (cdr xs) n)) 
             (cons x (loop (- i 1) x))))))