【问题标题】:Return smallest element in a list of numbers in Racket ISL?返回Racket ISL中数字列表中的最小元素?
【发布时间】:2016-12-06 23:05:58
【问题描述】:

我必须在 Racket 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)]
    [(

【问题讨论】:

    标签: algorithm list racket racket-student-languages


    【解决方案1】:

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

    【讨论】:

    • 哇,没想到这么简单!非常感谢!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2017-07-22
      • 2012-11-13
      • 1970-01-01
      • 2018-07-09
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多