问题描述
我想将元素 b
附加到列表 a
(假设是 (a1, a2, ... an)
),例如将数字 3
附加到 (1 2)
给出 (1 2 3)
I want to append the element b
to the list a
(let's say (a1, a2, ... an)
), e.g. appending the number 3
to (1 2)
gives (1 2 3)
到目前为止我一直在做(append a (list b))
,有点冗长不雅,不知道有没有更好"的方法...
So far I've been doing(append a (list b))
, which is kind of long and inelegant, so I wonder if there's a "better" way...
推荐答案
您是否正在逐项构建列表,一次一个项目?如果是这样,惯用的方法是向后构建列表,使用cons
,然后反转
最终结果:
Are you building a list piecemeal, an item at a time? If so, the idiomatic way to do this is to build the list backward, using cons
, and then reversing
the final result:
(define (map-using-cons-and-reverse f lst)
(let loop ((result '())
(rest lst))
(if (null? rest)
(reverse result)
(loop (cons (f (car rest)) (cdr rest))))))
或者,如果您的列表构建适用于右折叠"递归方法,那也是惯用的:
Alternatively, if your list-building is amenable to a "right-fold" recursive approach, that is also idiomatic:
(define (map-using-recursion f lst)
(let recur ((rest lst))
(if (null? rest)
'()
(cons (f (car rest)) (recur (cdr rest))))))
以上代码片段仅用于说明在一般情况下采用的解决方法;对于可以使用 fold 直接实现的东西,例如 map
,使用 fold 更为惯用:
The above code snippets are just for illustrating the solution approach to take in the general case; for things that are directly implementable using fold, like map
, using fold is more idiomatic:
(define (map-using-cons-and-reverse f lst)
(reverse (foldl (lambda (item result)
(cons (f item) result))
'() lst)))
(define (map-using-recursion f lst)
(foldr (lambda (item result)
(cons (f item) result))
'() lst))
这篇关于Scheme/Racket:将单个元素附加到列表末尾的最惯用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!