1

我一直在阅读 The Little Schemer,我开始对如何处理负数感到好奇。弄清楚如何构建一个函数来确定一个数字是负数还是正数,这似乎是一个很好的挑战。

到目前为止,我有这个解决方案:

(define negative?
  (lambda (a)
    (cond
      ((zero? a) #f)
      (else (negativeHelper (sub1 a) (add1 a))))))

(define negativeHelper
  (lambda (a b)
    (cond
      ((zero? a) #f)
      ((zero? b) #t)
      (else (negativeHelper (sub1 a) (add1 b))))))

这看起来工作得很好,但我的问题是是否可以在negative?没有辅助功能的情况下进行纠正?

4

1 回答 1

3

这可能不是您要寻找的答案,但“帮助”功能绝对没有问题。

你可能喜欢嵌套在negative?函数里面

(define (negative? x)
  (define (aux a b)
    (cond ((zero? a) #f)
          ((zero? b) #t)
          (else (aux (sub1 a) (add1 b)))))
  (aux x x))

验证结果

(negative? 4)  ; => #f
(negative? -4) ; => #t
(negative? 0)  ; => #f
于 2016-02-03T17:36:23.860 回答