开发者

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:

  1. an atom -> return it
  2. a cons with an atom as the CAR -> double it
  3. 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 consing them

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜