反向列表 - 方案 [英] reverse list - scheme

查看:33
本文介绍了反向列表 - 方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反转列表,这是我的代码:

I'm trying to reverse a list, here's my code:

(define (reverse list)
  (if (null? list) 
     list
      (list (reverse (cdr list)) (car list))))

所以如果我输入 (reverse '(1 2 3 4)),我希望它以 (4 3 2 1) 的形式出现,但现在它没有给我那个.我做错了什么,我该如何解决?

so if i enter (reverse '(1 2 3 4)), I want it to come out as (4 3 2 1), but right now it's not giving me that. What am I doing wrong and how can I fix it?

推荐答案

递归列表的自然方式并不是解决这个问题的最佳方式.使用@lancery 指出的已接受答案中建议的 append 也不是一个好主意 - 无论如何,如果您在 Scheme 中学习自己的方式,最好尝试自己实施解决方案,我会告诉你该怎么做,但首先是一个提示 - 不要使用 list 作为参数名称,这是一个内置过程,你会覆盖它.使用其他名称,例如 lst.

The natural way to recur over a list is not the best way to solve this problem. Using append, as suggested in the accepted answer pointed by @lancery, is not a good idea either - and anyway if you're learning your way in Scheme it's best if you try to implement the solution yourself, I'll show you what to do, but first a tip - don't use list as a parameter name, that's a built-in procedure and you'd be overwriting it. Use other name, say, lst.

通过辅助过程来反转列表更简单,该辅助过程累积结果的 head 每个元素的结果,这将具有反转列表的效果 - 顺便说一句,辅助程序是尾递归的.这是总体思路,填空:

It's simpler to reverse a list by means of a helper procedure that accumulates the result of consing each element at the head of the result, this will have the effect of reversing the list - incidentally, the helper procedure is tail-recursive. Here's the general idea, fill-in the blanks:

(define (reverse lst)
  (<???> lst '()))                       ; call the helper procedure

(define (reverse-aux lst acc)
  (if <???>                              ; if the list is empty
      <???>                              ; return the accumulator
      (reverse-aux <???>                 ; advance the recursion over the list
                   (cons <???> <???>)))) ; cons current element with accumulator

当然,在现实生活中你不会从头开始实现 reverse,有一个内置的 程序.

Of course, in real-life you wouldn't implement reverse from scratch, there's a built-in procedure for that.

这篇关于反向列表 - 方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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