Flatten a list using only the forms in “The Little Schemer”

后端 未结 3 1531
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 08:45

I\'m going through The LIttle Schemer to learn Scheme (as an old C programmer) and as an exercise I tried to write a procedure to flatten a list using only the form

3条回答
  •  隐瞒了意图╮
    2020-11-27 08:59

    Here's an attempt. It gets away with using cons and avoiding append, because it only chips away the first non-pair it can get to and conses that to the flatten of a new tail it has built. Sometimes it rewrites the list then just calls flatten again. Def not the most efficient way.

    Fixed code:

    (define (flatten x)
      (cond 
        ((null? x) x)
        ((and (pair? x) 
              (not (pair? (car x))))
         (cond 
           ((null? (car x)) (flatten (cdr x)))
           (else (cons (car x) (flatten (cdr x))))))
        ((and (pair? x)
              (pair? (car x)))
         (flatten (cons (caar x) 
                        (cons (cdar x) (cdr x)))))
        (else (cons x '()))))
    

提交回复
热议问题