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))

This works like:

(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)

How would I go about this?

解决方案

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)))))

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)))))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值