4
我知道你可以使用(> 3 2)
來比較Racket中的兩個參數。但是三個數字集呢?你可以使用類似如何比較球拍中的三個參數?
(define smallest-of-three
(lambda (a b c)
(cond (and (> a b) (> a c))a)))
例如?
謝謝
我知道你可以使用(> 3 2)
來比較Racket中的兩個參數。但是三個數字集呢?你可以使用類似如何比較球拍中的三個參數?
(define smallest-of-three
(lambda (a b c)
(cond (and (> a b) (> a c))a)))
例如?
謝謝
如果你想找到最低的三個數字的做到這一點:
(min a b c)
作爲一個更通用的解決方案,你也可以使用foldl
,像這樣:
(foldl (lambda (a b) ;; our comparison function
(if (< a b) a b))
a ;; our initial value
(list b c)) ;; the rest of our values
現在我們可以做比較複雜的比較了,因爲我們可以使用任何採用兩個參數並只返回其中一個參數的過程。
使用高階函數,我們甚至可以進一步概括如下:
(define (compare-multiple comp-func)
(lambda (first . rest)
(foldl comp-func ;; our comparison function
first ;; our initial value
rest))) ;; the rest of our values
;; I want to make my own min function
(define my-min (compare-multiple (lambda (a b) (if (< a b) a b)))
;; result is 1
(my-min 42 1 45)
上述程序是測試如果「A」是最大的三個數字中,違背了程序的名稱 –