首页 > 解决方案 > #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,所以我假设这意味着某些东西是错误的?如何修复此代码以使用条件表达式返回中间值?

标签: schemelisprepl.it

解决方案


我认为值得考虑一下你必须做多少测试来计算这些东西:要计算任何排序运算符下三个元素的极值,你需要做的比较不超过三个:

(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 个项目的中点。


推荐阅读