how do you append list of lists without using append in scheme?

痴心易碎 提交于 2019-12-12 04:51:51

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/26745466/how-do-you-append-list-of-lists-without-using-append-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!