gpt4 book ai didi

scheme - #f 在 repl.it 中输出方案结果

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:28 25 4
gpt4 key购买 nike

我正在做一些来自 Structure and Interpretation of Computer Programs 的问题

我的案例在 repl.it 解释器中输出 #f 作为有效结果。我正在申请 (and (not (max a b c)) (not (min a b c))) 以获得中间值。

我已经尝试重新排列中间函数的值。 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,所以我假设这意味着错误?如何修复此代码以使用条件表达式返回中间值?

最佳答案

我认为值得考虑您必须进行多少次测试才能计算这些东西:要在任何排序运算符下计算三个元素的极值,您只需进行不超过 3 次比较:

(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 项的中点是很有趣的。

关于scheme - #f 在 repl.it 中输出方案结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57504535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com