首页 > 解决方案 > 如何编写一个计算列表中增加的函数?

问题描述

在 Racket 中,我得到的任务是“编写一个函数 countIncreases,它接受一个数字列表并返回连续数字值增加的次数。例如,countIncreases '(1 3 2 4 5 1)应该返回 3,因为有三个增加:1 3、2 4、4 5。"

我编写了一个递归函数,基本情况是如果列表为空,则返回 0。我相信我的问题是正确地将一个值与下一个值进行比较。我应该使用 foldr 或 map 之类的标准库列表迭代函数来完成此任务吗?

我的代码和测试如下,错误信息截图附在这里

(define (countIncreases aList)
  (if (empty? aList)
       0
       (if (< (first aList) (rest aList))
           (+ 1 (countIncreases (rest aList)))
           (countIncreases (rest aList)))))

(check-expect (countIncreases '(1 3 2 4 5 1)) 3)
(check-expect (countIncreases '()) 0)
(check-expect (countIncreases '(1 2 3 4 5)) 4)
(check-expect (countIncreases '(5 4 3 2 1 2)) 1)

标签: recursionracket

解决方案


推荐阅读