如何反转Scheme中列表元素的顺序(How to reverse the order of elements of a list in Scheme)

编程入门 行业动态 更新时间:2024-10-27 02:22:52
如何反转Scheme中列表元素的顺序(How to reverse the order of elements of a list in Scheme)

我有一个函数来反转列表中元素的顺序,例如

(define (rvsl sequence) (foldl (lambda (x y) (cons y x)) '() sequence))

但是,当我在DrRacket中使用输入运行它时

(rvsl (list 2 3 4))

DrRacket告诉我这个

cons: second argument must be a list, but received empty and 2

有人可以给我一些想法来解决它吗?

提前致谢!

I got a function to reverse the order of the elements in a list, such as

(define (rvsl sequence) (foldl (lambda (x y) (cons y x)) '() sequence))

However, when I ran it in DrRacket with the input

(rvsl (list 2 3 4))

DrRacket told me this

cons: second argument must be a list, but received empty and 2

Could anybody please give me some ideas to solve it?

Thanks in advance!

最满意答案

您的代码的问题是您以错误的顺序传递参数 - 当使用cons构建列表时,第一个参数是我们想要在列表的开头粘贴的新元素,第二个参数是到目前为止我们已经建立的列表。

话虽如此,使用foldl反转列表有点简单,你根本不需要使用append - 实际上,当cons足够时使用append是一个不好的做法:

(define (rvsl sequence) (foldl cons '() sequence))

为什么会这样? 让我们这次重写更明确的函数:

(define (rvsl sequence) (foldl (lambda (current accumulated) (cons current accumulated)) '() sequence))

现在我们可以看到lambda过程接收两个参数:输入列表中的current元素,以及到目前为止的accumulated值 - 好的参数名称在世界上有所不同! 这比调用参数x和y要清楚得多,后者对它们一无所知。

在这种情况下,我们只想在累计值的头部(从一个空列表开始)中获取当前元素,从而产生一个反向列表作为输出。 鉴于lambda过程接收两个参数并以相同的顺序传递它们,我们可以简化整个过程并将cons过程作为参数传递。

The problem with your code is that you're passing the parameters in the wrong order - when using cons to build a list, the first parameter is the new element we want to stick at the beginning of the list, and the second one is the list we've built so far.

Having said that, reversing a list using foldl is a bit simpler and you don't need to use append at all - in fact, it's a bad practice using append when cons suffices:

(define (rvsl sequence) (foldl cons '() sequence))

Why this works? let's rewrite the function being more explicit this time:

(define (rvsl sequence) (foldl (lambda (current accumulated) (cons current accumulated)) '() sequence))

Now we can see that the lambda procedure receives two parameters: the current element in the input list, and the accumulated value so far - good parameter names make all the difference in the world! this is much, much clearer than calling the parameters x and y, which says nothing about them.

In this case, we just want to cons the current element at the head of the accumulated value (which starts as an empty list), hence producing a reversed list as the output. Given that the lambda procedure receives two parameters and passes them in the same order to cons, we can simplify the whole thing and just pass the cons procedure as a parameter.

更多推荐

本文发布于:2023-08-07 11:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464296.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   元素   列表   Scheme   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!