问题描述
我正在尝试开发一个简单的函数,该函数返回Lisp中的最小和最大值.到目前为止,我已经有一个适用于单个Lisp的基本解决方案,下面是代码
I'm trying to develop a simple function that returns the smallest and largest value in Lisp. So far I have the basic solution working for a single Lisp and here is the code
(defun get-smallest-large (lst &optional (smallest 0) (largest 0))
(setf smallest (first lst))
(setf largest 0)
(dolist (nxt lst)
(if (< nxt smallest)
(setf smallest nxt)
(if (> nxt largest)
(setf largest nxt))))
(cons smallest largest))
它的工作原理是:
(defun get-smallest-large '(1 2 -1 3))
= (-1 . 3)
现在,我一辈子都无法弄清楚如何更改此解决方案以处理嵌套列表,因此,例如,我输入了以下内容:
Now, I can't for the life of me figure out how to change this solution to deal with nested lists so for instance, I entered this:
(defun get-smallest-large '(5 (-2 20 (3)) -6 (-7 13)))
= (-7 . 20)
我将如何处理?
推荐答案
这里是一种处理方法:当递归到子列表时,将返回值当作外部列表的元素一样进行处理.示例(在Scheme中,这是我的母语";要求 SRFI 26 ):
Here's one way you can approach it: when you recurse into sublists, process the return values as if they were elements of the outer list also. Example (in Scheme, which is my "native language"; requires SRFI 26):
(define (min-max x (min #f) (max #f))
(cond ((null? x) (if min (values min max) (values)))
((cons? x) (call-with-values (cut min-max (car x) min max)
(cut min-max (cdr x) <...>)))
(else (values (if (and min (< min x)) min x)
(if (and max (> max x)) max x)))))
这是相同的 direct 常见Lisp翻译,我的意思是它根本不是惯用的CL,而是为不熟悉Scheme的CL程序员提供的,以了解Scheme代码的用途.尤其是,即使CL并未提供适当的尾部递归的Scheme要求,也是如此.
And here's a direct Common Lisp translation of same, by which I mean that it's not idiomatic CL at all, but presented for CL programmers unfamiliar with Scheme to get an idea of what the Scheme code does. In particular, the Scheme requirement for proper tail recursion still holds, even though CL does not provide that.
(defun min-max (x &optional min max)
(cond ((null x) (if min (values min max) (values)))
((consp x)
(multiple-value-call #'min-max (cdr x) (min-max (car x) min max)))
(t (values (if (and min (< min x)) min x)
(if (and max (> max x)) max x)))))
这篇关于如何在Lisp中的嵌套列表中打印最大和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!