# 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