RodoM
RodoM

Reputation: 63

Duplicate n times an element from a list in Racket

for example:

(duplicate 3 (list 1 2 3)) = (list 1 1 1 2 2 2 3 3 3)

i tried this:

(define (duplicate n l)
  (cond [(zero? n) empty]
        [else (cons l (duplicate (sub1 n) l))]))

but it gives me:

(duplicate 2 (list 1 2)) = (list (list 1 2) (list 1 2))

Upvotes: 0

Views: 979

Answers (2)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 10010

(define (duplicate n x)
  "Repeat x n times."
  (cond [(zero? n) empty]
        [else (cons x (duplicate (sub1 n) x))]))

(define (mappend fn . lists)                                                                
  "map but appending the results."                                                                
  (apply append (apply map fn lists)))

(define (duplicate-list n l)
  "duplicate each element in l."
  (mappend (lambda (x) (duplicate n x)) l))

Then

(duplicate-list 3 (list 1 2 3))
;; '(1 1 1 2 2 2 3 3 3)

Upvotes: 0

Sylwester
Sylwester

Reputation: 48775

You are actually half way. What you have created is something that takes one element and a count and makes a list of that many elements.

(duplicate 3 'e) ; ==> (3 3 3)

That means that you can use that:

(duplicate-list 3 l) 
; ==> (append (duplicate 3 (car l))
;             (duplicate-list 3 (cdr l)))

Upvotes: 1

Related Questions