CLISP-反转简单列表 [英] CLISP - Reversing a simple list

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

问题描述

我必须反转简单(单维)列表的元素.我知道有一个内置的反向函数,但是我不能为此使用它.

I have to reverse the elements of a simple (single-dimension) list. I know there's a built-in reverse function but I can't use it for this.

这是我的尝试:

(defun LISTREVERSE (LISTR)
    (cond
        ((< (length LISTR) 2) LISTR) ; listr is 1 atom or smaller
        (t (cons (LISTREVERSE (cdr LISTR)) (car LISTR))) ; move first to the end
    )
)

输出非常接近,但是是错误的.

Output pretty close, but is wrong.

[88]> (LISTREVERSE '(0 1 2 3)) 
((((3) . 2) . 1) . 0)

所以我尝试使用append代替cons:

(t (append (LISTREVERSE (cdr LISTR)) (car LISTR)))

但是出现了这个错误:

*** - APPEND: A proper list must not end with 2

有帮助吗?

推荐答案

我可以给你一些指导,因为这看起来像是作业:

I can give you a couple of pointers, because this looks like homework:

  • 递归的基本情况是列表为空(空),而列表中的元素少于两个时为 not .
  • 考虑使用一个额外的参数定义一个辅助函数,该参数是在空列表中初始化的累加器".对于原始列表中的每个元素,将其cons置于累加器的开头.输入列表为空时,返回累加器
  • The base case of the recursion is when the list is empty (null), and not when there are less than two elements in the list
  • Consider defining a helper function with an extra parameter, an "accumulator" initialized in the empty list. For each element in the original list, cons it at the head of the accumulator. When the input list is empty, return the accumulator

顺便提一下,上述解决方案是尾递归的.

As an aside note, the above solution is tail-recursive.

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

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