计划功能以反向列表 [英] Scheme function to reverse a list
问题描述
对于我的编程语言类,我应该在Scheme中编写一个函数以反转列表,而无需使用预制的反转函数.到目前为止,我得到的是
For my programming languages class I'm supposed to write a function in Scheme to reverse a list without using the pre-made reverse function. So far what I got was
(define (reverseList lst)
(COND
((NULL? lst) '())
(ELSE (CONS (reverseList(CDR lst)) (CAR lst)))
))
我遇到的问题是,如果我输入列表,可以说(a b c)
它给了我(((() . c) . b) . a)
.
The problem I'm having is that if I input a list, lets say (a b c)
it gives me (((() . c) . b) . a)
.
我应该如何在没有多套括号和.
的情况下获得一个干净的列表?
How am I supposed to get a clean list without multiple sets of parenthesis and the .
's?
推荐答案
实现的问题是cons
没有收到 list 作为第二个参数,所以答案是重建不是正确的列表,请记住:要正确构建列表,是通过cons
将元素与列表一起构建,而最后一个列表为空.
The problem with your implementation is that cons
isn't receiving a list as its second parameter, so the answer you're building isn't a proper list, remember: a proper list is constructed by cons
ing an element with a list, and the last list is empty.
一个可能的解决方法是使用一个辅助函数,该函数在累加器参数中构建答案,cons
反向添加元素-顺便说一下,此解决方案是尾递归:
One possible workaround for this is to use a helper function that builds the answer in an accumulator parameter, cons
ing the elements in reverse - incidentally, this solution is tail recursive:
(define (reverse lst)
(reverse-helper lst '()))
(define (reverse-helper lst acc)
(if (null? lst)
acc
(reverse-helper (cdr lst) (cons (car lst) acc))))
(reverse '(1 2 3 4 5))
=> '(5 4 3 2 1)
这篇关于计划功能以反向列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!