2016-12-06 79 views
1

我必须在Racket ISL中编写一个函数,它需要一个数字列表并返回列表中的最小数字。最小和最大值都是不允许的。我想我在这里有一个开始;显然需要递归。返回球拍ISL中数字列表中的最小元素?

最终我会用这个函数来创建一个抽象的。

(check-expect (find-smallest (list 3 8 4 9 2 0 1)) 0) 
(check-expect (find-smallest (list 2 3 4 5 6)) 2) 
(check-expect (find-smallest (list 58 37 28 37 58 92 24)) 24) 
(check-expect (find-smallest (list 19 38 46 85 19 38 19)) 19) 

;; find-smallest: list of numbers -> number 
;; consumes a list of numbers and returns the 
;; smallest number in the list 
(define (find-smallest lon) 
    (cond 
    [(empty? (rest lon)) (first lon)] 
    [(

回答

1

它看起来像你的基本情况是好的。您的默认情况可以如下所示:您可以使用find-smallest来查找列表中剩余部分的最小值,并将其与第一个元素进行比较,例如。与<。最小的应该是结果。

+0

哇,我不知道它是这么简单!非常感谢你! –

0

你也可以使用内部命名让环和一个临时变量来存储最小值找到列表中最小的数字:

(define (find-smallest l) 
    (let loop ((l l) 
      (sm (first l))) ; start with first of list as smallest 
    (cond 
     [(empty? l) sm] 
     [(< sm (first l)) 
     (loop (rest l) sm)] 
     [else 
     (loop (rest l) (first l))])))