【问题标题】:Segmentation fault when trying to reverse a list尝试反转列表时出现分段错误
【发布时间】:2014-12-07 15:44:30
【问题描述】:

我正在学习 Common Lisp,我一直在尝试编写一个函数来反转列表。这是函数,但每次我尝试运行它时都会收到“分段错误(核心转储)”

(defun reverseList(x)
  (if (cdr x)
      (cons (reverseList x) (car x))
    (car x)))


(reverseList '(1 2 3))

【问题讨论】:

  • 你得到了一个stackoverflow(原文如此!),因为你的代码无限地使用相同的列表调用reverseList。它是非终止的。
  • 啊,谢谢。我的意思是把它传递给 cdr x。

标签: lisp common-lisp


【解决方案1】:

我认为这会起作用:

(define reverseList(lambda(x)(
                          if (null? (cdr x))
                             (cons (car x) '())
                             (append (reverseList (cdr x)) (cons (car x) '()))                                  
                             )
                 )
)

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 1970-01-01
    • 2019-10-17
    • 2015-08-27
    • 2023-03-11
    • 1970-01-01
    • 2019-12-05
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多