Can anyone explain the following schema code?

I listened to a series of lectures on the programming paradigm at Stanford , but the following code confuses me (from lecture 20). Will someone explain, in turn, what this does?

Thanks.

(define (flatten sequence)
  (cond ((null? sequence) '())
        ((list? (car sequence)) (append (flatten (car sequence))
                                        (flatten (cdr sequence))))
        (else (cons (car sequence)
                    (flatten (cdr sequence))))))
+3
source share
2 answers
# 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))))))

I pretty-printed it (inserted some new lines and backed off the code to show its structure), and also replaced it '()with (list)(which has the same meaning) to prevent the code from being allocated incorrectly.

+1 what is in the way? I would appreciate it if you could explain other keywords as well. thanks

"cons-ing", 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) - (cons 1 (cons 2 (cons 3 (cons 4 '() )))).

, , car cdr. (car <list>) first head <list> (cdr <list>), rest tail <list>. , (car (list 1 2 3 4)) 1, (cdr (list 1 2 3 4)) (list 2 3 4).

, .

+7
  • ,

  • () (cdr)

+1

Source: https://habr.com/ru/post/1719195/


All Articles