方案/球拍:将元素添加到列表末尾的最惯用方式 [英] Scheme/Racket: most idiomatic way to append single element to end of list
问题描述
我想将元素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
向后构建列表,然后使用reversing
最终结果:
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))
这篇关于方案/球拍:将元素添加到列表末尾的最惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!