2017-04-07 73 views
0

我正在寫一個函數來複制列表中的所有項目,以便像(a(b c))這樣的列表變成(a a(b b c c)),但是我的函數返回(a b b c c)。我如何確保我保留內部列表結構?這裏是我當前的代碼:複製時維護列表結構

(define double 
    (lambda (l) 
    (cond ((null? l) '()) 
      ((list? l) (append (double (car l)) (double (cdr l)))) 
      (else (append (list l) (list l))) 
    ) 
)) 
+0

如果 「重複所有列表中的項目」 不應該將其返回'(一A(B C)(B C))'? – jakeehoffmann

+0

也許我沒有盡我所能將它說出來,但我希望它能夠複製列表中的每個項目 – user1775500

回答

2

爲了保持列表的結構,你必須避免使用append。這是一個實現:

(define (double lst) 
    (cond 
    [(null? lst) empty] 
    [(list? (car lst)) 
    (cons (double (car lst)) 
      (double (cdr lst)))] 
    [else 
    (cons (car lst) (cons (car lst) 
      (double (cdr lst))))])) 

例如,

> (double '(a (b c) ((a b) (c d)))) 
'(a a (b b c c) ((a a b b) (c c d d))) 
0

淺拷貝:

(define (copy-list lst) 
    (map values lst)) 

當然map的,是這樣的一個list參數:

(define (map f lst) 
    (if (null? lst) 
     '() 
     (cons (f (car lst)) 
      (map f (cdr lst))))) 

深拷貝:

(define (copy-tree tree) 
    (accumulate-tree tree values cons '())) 

這是accumulate-tree是怎麼做:

(define (accumulate-tree tree term combiner null-value) 
    (let rec ((tree tree)) 
    (cond ((null? tree) null-value) 
      ((not (pair? tree)) (term tree)) 
      (else (combiner (rec (car tree)) 
          (rec (cdr tree)))))))