1
votes

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?

1
You need to condition on if the current element itself is a list or not. If it is, it shouldn't duplicate, but recursively call the duplicate function with the inner list as argument. Only when you're at the lowest level should duplication happen. I'm not that familiar with Racket syntax, but I'll try and figure it out.Mads Nielsen

1 Answers

1
votes

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)