How can I recursively print the elements of a list twice?
I need to write a recursive function that prints out the elements of a list twice. For example, rdouble '(1 2 3) would print (1 1 2 2 3 3) and rdouble'(1 (2 3) 4) would 开发者_StackOverflowprint (1 1 (2 2 3 3) 4 4).
So far I have:
(defun rdouble(struct)
(cond
((atom struct) struct)
(t (cons (rdouble (car struct)) (cons (car struct)
(rdouble (cdr struct))
)))))
This works fine for the first example but prints
(1 1 (2 2 3 3) (2 3) 4 4)
for the second example. How do I continue to print out each element twice but not reprint (2 3)? What am I doing wrong and how can I fix it?
The expression has THREE different cases:
- an atom -> return it
- a cons with an atom as the CAR -> double it
- a cons with a cons as the CAR -> walk down
Your code handles only two cases, where your second case mixes 2 and 3.
the reason it is causing the problems you are experiencing is that given ((1 2) 3)
your code recurses into (1 2)
, which correctly becomes (1 1 2 2)
and then adds (1 2)
(being the car
in the first call) after the (1 1 2 2)
giving ((1 1 2 2) (1 2) ...)
what would be best is to make rdouble
always return a list, and append
those lists together instead of cons
ing them
精彩评论