I have been listening to Stanford’s programming paradigm lecture series, but I’m confused by the following code (from lecture 20). Would someone explain, line by line, what this is doing?
Thanks.
(define (flatten sequence)
(cond ((null? sequence) '())
((list? (car sequence)) (append (flatten (car sequence))
(flatten (cdr sequence))))
(else (cons (car sequence)
(flatten (cdr sequence))))))
I pretty-printed it (inserted some newlines and indented the code to show its structure) and also replaced
'()with(list)(which has the same value) just to prevent the code from being highlighted incorrectly.When I say cons-ing I’m just referring to the
consprocedure. When you see(cons <expression> <list>)where<expression>is any Scheme expression or value and<list>is any Scheme expression that evaluates to a list,conswill return the<list>with the value of the<expression>tacked on the front of it. For example,(cons 1 (list 2 3 4))returns the list(list 1 2 3 4). In fact,(list 1 2 3 4)in Scheme is just a short way of writing(cons 1 (cons 2 (cons 3 (cons 4 '() )))).The other two words you might have trouble with are
carandcdr. You can think of(car <list>)as meaning the first element or head of the<list>, and(cdr <list>)as meaning the rest of the elements or tail of the<list>. For example,(car (list 1 2 3 4))returns the value1, and(cdr (list 1 2 3 4))returns the list(list 2 3 4).If you need any help with other keywords, let me know.