[英]Determining if a number is negative in Scheme with one function
我一直在經歷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?
沒有輔助功能?
這可能不是您正在尋找的答案,但“幫助”功能絕對沒有錯。
你可能喜歡在negative?
內嵌套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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.