scheme - 返回其列表参数中最短的方案函数
问题描述
我正在尝试创建一个方案函数,该函数将返回其参数列表中最短的。
(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8)) 应该编译 (4)。
这是我目前所拥有的......
(define (shortest lst) (foldl (lambda (e r) (if (or (not r) (< e r)) e r))
#f
lst))
它给出了错误数量不匹配。
解决方案
您的答案接近正确,但您需要实际比较子列表的长度,并确保您的过程接受可变数量的参数。这应该可以工作,只需进行最少的更改:
; the . is for accepting multiple args
(define (shortest . lst)
(foldl (lambda (e r)
; notice how we compare the lengths
(if (or (not r) (< (length e) (length r))) e r))
#f
lst))
它按预期工作:
(shortest '(1 2) '(2 3 4) '(4) '(5 6 7 8))
=> '(4)
(shortest '())
=> '()
(shortest)
=> #f
推荐阅读
- c# - 为什么某些带有双反斜杠的路径抛出找不到路径异常的一部分?
- javascript - Firebase - 电子邮件验证后的事件
- python - 从 Zapier 中的 Thread 解析电子邮件回复
- angular - 如何在新的 observable 发出值之前显示 prev observable 的数据
- python - 如何使用 Selenium 在 Facebook 上单击按钮
- react-native - Android NFC:如何在 NFC TAG 上设置密码和身份验证?
- python - nltk:构建 docker 时无法下载包 punkt
- java - 如何在java中收集协程流?
- sidekiq - 带有 sidekiq 的 Crontan 调度程序 - 尝试将其设置为东部时间每天下午 2 点
- javascript - 使用 Node.JS、EJS 和前端 JS 构建可重用代码的最佳方式?