Scheme/Racket:将单个元素附加到列表末尾的最惯用的方法 [英] Scheme/Racket: most idiomatic way to append single element to end of list

查看:31
本文介绍了Scheme/Racket:将单个元素附加到列表末尾的最惯用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将元素 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:将单个元素附加到列表末尾的最惯用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆