# 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 '()))))
的簡短方法。
您可能遇到的其他兩個詞是car
和cdr
。你可以認爲(car <list>)
爲意指第一元素或頭<list>
,並(cdr <list>)
爲是指元素其餘或尾的<list>
。例如,(car (list 1 2 3 4))
返回值1
,而(cdr (list 1 2 3 4))
返回列表(list 2 3 4)
。
如果您需要其他關鍵字的幫助,請告訴我。
從我的大學時代我想念計劃 – Martin 2009-10-04 01:30:52