gpt4 book ai didi

lisp - LISP 中的快速排序

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:37 25 4
gpt4 key购买 nike

我正在尝试使用 LISP 进行快速排序,但我在函数输出方面遇到了问题。

(defun qsort (L)
(cond
((null L) nil)
(t(append
(qsort (list< (car L) (cdr L)))
(cons (car L) nil)
(qsort (list>= (car L) (cdr L)))))))

(defun list< (a b)
(cond
(( or(null a)(null b) nil))
(( < a (car b)) (list< a (cdr b)))
(t(cons (car b) (list< a (cdr b))))))

(defun list>= (a b)
(cond
(( or( null a)(null b) nil))
(( >= a (car b)) (list> a (cdr b)))
(t(cons (car b) (list> a (cdr b))))))

我的问题是当 list<list>= 完成列表时总是以 .T 结尾。例如:

> (list< '4 '(1 5 3 8 2))
Entering: LIST<, Argument list: (4 (1 5 3 8 2))
Entering: LIST<, Argument list: (4 (5 3 8 2))
Entering: LIST<, Argument list: (4 (3 8 2))
Entering: LIST<, Argument list: (4 (8 2))
Entering: LIST<, Argument list: (4 (2))
Entering: LIST<, Argument list: (4 NIL)
Exiting: LIST<, Value: T
Exiting: LIST<, Value: (2 . T)
Exiting: LIST<, Value: (2 . T)
Exiting: LIST<, Value: (3 2 . T)
Exiting: LIST<, Value: (3 2 . T)
Exiting: LIST<, Value: (1 3 2 . T)
(1 3 2 . T)

为什么 (4 NIL) 评估为 T?

最佳答案

关于 list< 的问题,还有 list>= , 位于 ((or ( null a)(null b) nil)) ,应该是(( or( null a)(null b)) nil) .备注nil被移出条件作为返回值。

此外,关于 list>= 的定义你调用list> , 但我肯定你的意思是 list>=相反。

我还建议一些 indentation解决 lisp 的易读性问题,如下所示

(defun qsort (L)
(cond
((null L) nil)
(t
(append
(qsort (list< (car L) (cdr L)))
(cons (car L) nil)
(qsort (list>= (car L) (cdr L)))))))

(defun list< (a b)
(cond
((or (null a) (null b)) nil)
((< a (car b)) (list< a (cdr b)))
(t (cons (car b) (list< a (cdr b))))))

(defun list>= (a b)
(cond
((or (null a) (null b)) nil)
((>= a (car b)) (list>= a (cdr b)))
(t (cons (car b) (list>= a (cdr b))))))

一些测试如下:

(list< '4 '(1 5 3 8 2))
=> (1 3 2)

(list>= '4 '(1 5 3 8 2))
=> (5 8)

(qsort '(1 5 3 8 2))
=> (1 2 3 5 8)

关于lisp - LISP 中的快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19082032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com