Loc Thien Tran
Loc Thien Tran

Reputation: 35

Racket duplicator function

I'm writing a duplicator function using racket. The duplicator function takes a nested list of symbols and numbers L, and produces a nested list of symbols and numbers by "immediately duplicating" each atom (symbol or number) at all levels. For example: (duplicator '(a 1 b 2 c 3)) produces (a a 1 1 b b 2 2 c c 3 3), (duplicator '( (a 1) b ((c)) 2) produces ( (a a 1 1) b b ((c c)) 2 2).

Here is my function:

(define (duplicator ls)
  (if (null? ls)
      '()
      (cons (car ls)
            (cons (car ls)
                  (duplicator (cdr ls))))))

The problem I have is the output for (duplicator '( (a 1) b ((c)) 2)) is '((a 1) (a 1) b b ((c)) ((c)) 2 2), which is not what I want. Can anyone tell me how to get it right, please?

Upvotes: 1

Views: 218

Answers (1)

Renzo
Renzo

Reputation: 27414

Here is a solution:

(define (duplicator ls)
  (cond ((null? ls) '())
        ((list? (car ls)) (cons (duplicator (car ls)) (duplicator (cdr ls))))
        (else (cons (car ls) (cons (car ls) (duplicator (cdr ls)))))))

(duplicator '((a 1) b ((c)) 2))  ; produces ((a a 1 1) b b ((c c)) 2 2)

Upvotes: 1

Related Questions