2009-10-03 86 views
3

我一直在聽斯坦福大學的programming paradigm lecture series,但我很困惑下面的代碼(第20講)。是否有人會逐行解釋這是做什麼的?有人可以解釋下面的Scheme代碼嗎?

謝謝。

(define (flatten sequence) 
    (cond ((null? sequence) '()) 
     ((list? (car sequence)) (append (flatten (car sequence)) 
             (flatten (cdr sequence)))) 
     (else (cons (car sequence) 
        (flatten (cdr sequence)))))) 
+0

從我的大學時代我想念計劃 – Martin 2009-10-04 01:30:52

回答

7
# define a procedure 'flatten' that takes a list 'sequence' 
(define (flatten sequence) 
    # if the 'sequence' is empty, return an empty list 
    (cond ((null? sequence) (list)) 
     # if the first element of 'sequence' is itself a list, return a new list 
     # made by appending the flattened first element of 'sequence' with the 
     # flattened rest of the 'sequence' 
     ((list? (car sequence)) 
     (append (flatten (car sequence)) 
       (flatten (cdr sequence)))) 
     # if the first element of 'sequence' is not a list, return a new list 
     # made by cons-ing that element with the flattened rest of the 'sequence' 
     (else 
     (cons (car sequence) 
       (flatten (cdr sequence)))))) 

我適合打印它(插入一些新行和縮進的代碼,以顯示其結構),並且還替換'()(list)(其具有相同的值)只是以防止不正確地強調了代碼。

+1什麼是缺點?如果你解釋其他關鍵字,我會很感激。謝謝

當我說缺點時,我只是指cons程序。當你看到(cons <expression> <list>)哪裏<expression>是任何方案表達式或值和<list>的任何計劃表達式,其值的列表,cons將與的<expression>上漲在它前面的值返回<list>。例如,(cons 1 (list 2 3 4))返回列表(list 1 2 3 4)。實際上,Scheme中的(list 1 2 3 4)只是寫作(cons 1 (cons 2 (cons 3 (cons 4 '()))))的簡短方法。

您可能遇到的其他兩個詞是carcdr。你可以認爲(car <list>)爲意指第一元素或<list>,並(cdr <list>)爲是指元素其餘<list>。例如,(car (list 1 2 3 4))返回值1,而(cdr (list 1 2 3 4))返回列表(list 2 3 4)

如果您需要其他關鍵字的幫助,請告訴我。

+1

哦,剛想起方案註釋以分號。但是當我將八角形更改爲分號時,突出顯示會變得混亂...... – 2009-10-03 23:33:09

+0

+1什麼是缺點?如果你解釋其他關鍵字,我會很感激。謝謝 – vehomzzz 2009-10-04 02:35:49

+0

謝謝@Jeremy Ruten - 你似乎知道你的計劃! – vehomzzz 2009-10-04 20:19:47

1
  1. 定義函數用於平一個 序列

  2. 對於空序列,則返回空

  3. 如果列表的頭(汽車)是 序列返回 扁平化的結果它附加到 平坦的尾巴(cdr)

  4. 否則追加頭部平鋪尾部

相關問題