recursion - 如何编写一个计算列表中增加的函数?
问题描述
在 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)
解决方案
推荐阅读
- angular - 在 Angular 模板中访问联合类型的属性
- ios - 在连接到 Focusrite 2i2 的 AKFrequencyTracker 上获得奇怪的频率读数
- reactjs - React useState hook - 更新状态时何时使用先前的状态?
- android - 如何在 Android Studio 上使用应用内购买销售图片
- scala - 单位类型的所有值都可以用单位创建吗?
- google-chrome - Pyppeteer 超时后查询页面内容?
- git - 在分离头时将多个提交放入新分支
- flutter - Flutter Extract Method vs. Extract Widget vs. 在androidStudio中提取Flutter Widget
- javascript - TypeScript:为什么我的过滤方法无法缩小类型并从数组中消除未定义和错误
- ios - 修复警告:无法在 (Project.UnderlinedTextField) 上设置 (lineColor) 用户定义的检查属性