2009-10-03 92 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. 否则追加头部平铺尾部

相关问题