how do you append list of lists without using appe

2019-08-31 08:41发布

Say you want append these list of lists and output a single list that contains all the numbers

(append-lists (list (list 1 2) 
                    (list 4 5) 
                    (list 10 19))) =>    (list 1 2 4 5 10 19) 

If using trivial append, i can do this,

((define (append-lists llon)
     (cond
        [(empty? llon) empty]
        [(cons? llon)  (cons (first llon)
                       (append-lists (rest llon)))]))

But how to get the same output without using append just by recursion?

标签: scheme
1条回答
何必那么认真
2楼-- · 2019-08-31 09:36

This is a special case of flattening. Some Scheme implementation feature a build-in flatten procedure; if not, a general flattening algorithm is :

(define (flatten sxp)
  (let loop ((sxp sxp) (res '()))
    (cond
      ((null? sxp) res)
      ((pair? sxp) (loop (car sxp) (loop (cdr sxp) res)))
      (else        (cons sxp res)))))

Testing:

> (flatten (list (list 1 2) (list 4 5) (list 10 19)))
'(1 2 4 5 10 19)
> (flatten (list (list 1 2) 'a (list 4 5) 'b (list 10 19)))
'(1 2 a 4 5 b 10 19)
查看更多
登录 后发表回答