如何在不使用 append in scheme 的情况下附加列表列表? [英] how do you append list of lists without using append in scheme?
本文介绍了如何在不使用 append in scheme 的情况下附加列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设你想追加这些列表并输出一个包含所有数字的列表
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)))]))
但是如何在不使用 append 的情况下仅通过递归获得相同的输出?
But how to get the same output without using append just by recursion?
推荐答案
这是一个扁平化的特例.一些 Scheme 实现具有内置的 flatten
过程;如果没有,一般的展平算法是:
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)))))
测试:
> (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)
这篇关于如何在不使用 append in scheme 的情况下附加列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文