我一直在听斯坦福大学的编程范例讲座系列,但我对下面的代码感到困惑(来自第20讲).有人会逐行解释这是做什么的吗?
谢谢.
(define (flatten sequence)
(cond ((null? sequence) '())
((list? (car sequence)) (append (flatten (car sequence))
(flatten (cdr sequence))))
(else (cons (car sequence)
(flatten (cdr sequence))))))
Run Code Online (Sandbox Code Playgroud)
# 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))))))
Run Code Online (Sandbox Code Playgroud)
我漂亮地打印它(插入一些换行符并缩进代码以显示其结构)并且还替换'()为(list)(具有相同值)以防止代码被错误地突出显示.
+1什么是供应?如果您解释其他关键字,我将不胜感激.谢谢
当我说有关时,我只是指的是cons程序.当你看到(cons <expression> <list>)这里<expression>的任何计划表达式或值,<list>是任何计划表达式,其值的列表,cons将返回<list>与价值<expression>上涨了它的前面.例如,(cons 1 (list 2 3 4))返回列表(list 1 2 3 4).事实上,(list 1 2 3 4)在Scheme中只是一种简短的写作方式(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).
如果您对其他关键字有任何帮助,请与我们联系.