在Scheme中查找列表的最大值和最小值

时间:2012-04-19 18:58:17

标签: list scheme racket

我需要找到列表的最大值和最小值,然后添加一个新列表。到目前为止,这是我的代码:

(define alist '(18 39 57 -4 0)

(define (nMax alist)
  (if (null? (cdr alist))
      (car alist)
      (if (> (car alist) (nMax (cdr alist)))
          (car alist)
          (nMax (cdr alist)))))

(define (nMin alist)
  (if (null? (cdr alist))
      (car alist)
      (if (< (car alist) (nMin (cdr alist)))
          (car alist)
          (nMin (cdr alist)))))

现在我被卡住了。如何在新列表中添加nMin + nMax?我的输出应该是这样的:

'(57 -4)

2 个答案:

答案 0 :(得分:6)

试试这个:

(define alist '(18 39 57 -4 0))

(define (max-min alist)
  (list (nMax alist)
        (nMin alist)))

(max-min alist)
> '(57 -4)

答案 1 :(得分:0)

(cons (nMax alist) (cons (nMin alist) '()))

这样的东西