scheme - #f 输出 repl.it 中的方案结果
问题描述
我的案例在 repl.it 解释器中输出 #f 作为有效结果。我正在应用 (and (not (max abc)) (not (min abc))) 来获得中间值。
我尝试重新排列 mid 函数的值。max 和 min 函数工作正常。
(define (max a b c)
(cond
((and(>= a b)(>= a c)) a)
((and(>= b a)(>= b c)) b)
((and(>= c a)(>= c b)) c)
))
(define (min a b c)
(cond
((and(<= a b)(<= a c)) a)
((and(<= b a)(<= b c)) b)
((and(<= c a)(<= c b)) c)
))
(define (mid a b c)
(and
(not (max a b c))
(not (min a b c))
))
(mid 10 8 6)
repl.it 方案解释器的输出是:
=> #f
我预计会出现某种错误或数字值,但此代码返回绿色#f,所以我假设这意味着某些东西是错误的?如何修复此代码以使用条件表达式返回中间值?
解决方案
我认为值得考虑一下你必须做多少测试来计算这些东西:要计算任何排序运算符下三个元素的极值,你需要做的比较不超过三个:
(define (extremum/3 ordered? a b c)
;; find the extremum of three elements under ordered?
(cond ((and (ordered? a b) (ordered? a c)) a)
((ordered? b c) b)
(else c)))
有了这个通用函数,您现在可以轻松定义 max/3 和 min/3 :
(define (max/3 a b c)
(extremum/3 >= a b c))
(define (min/3 a b c)
(extremum/3 <= a b c))
计算三个元素的中点也需要不超过三个测试:
(define (mid/3 a b c)
(if (>= a b)
(if (>= a c)
;; a is greatest, so we need to pick b or c
(if (>= b c) b c)
;; a is the mid point
a)
(if (>= a c)
;; a is the mid point
a
;; a is the minimum, pick b or c
(if (>= c b) b c))))
有趣的是,您需要进行多少次比较才能找到 n 个项目的中点。
推荐阅读
- javascript - javascript 中有没有像 PHP 的 http_build_query 函数这样的函数?
- bash - 如何使用 shell 脚本回答运行时问题并期待
- ansible - 无法启动 ansibled.service:未找到单元
- excel - 使用 Powershell 进行 Excel 操作
- javascript - 如何重构重复的条件 Vue.js 代码?
- python - 如何在没有输出列的新文件上使用此机器学习模型?
- python - 我对教程 djangogirls 的结尾有疑问 https://tutorial.djangogirls.org/fr/django_forms/
- .htaccess - 检查是否在 htaccess 中设置了规范标头
- nginx - Nginx反向代理多个位置未加载
- angularjs - AngularJs 部署站点 SyntaxError:意外的标识符