在 Scheme 中编写最小值过程的另一种方法? [英] Another way of writing a mimum value procedure in Scheme?
问题描述
因此,如果我有以下内容,它将返回一组四个数字中的最小值:
So if i have the following, which returns the smallest value out of a set of four numbers:
(define (minimum2 a b c d)
(cond ((and (< a b) (< a c) (< a d)) a)
((and (< b c) (< b d)) b)
((< c d) c)
(else d)))
但是,我想这样写,我比较 a 和 b 并找到两者之间的最小值,然后比较 c 和 d,并找到它们之间的最小值,然后将这两个最小值放在一起以找到实际最小值.如果我写的东西很难理解,可以把它想象成一个锦标赛括号,其中 a 玩" b,赢家玩 c 和 d 之间的另一个赢家.预先感谢您的帮助!
But, I want to write it so that I compare a to b and find the smallest value between those two, then compare c and d, and find the smallest value between those, and then compare those two smallest values together to find the actual minimum. If what I wrote was tough to understand, think of it like a tournament bracket, where a "plays" b, and the winner plays the other winner between c and d. Thank you in advance for the help!
推荐答案
这是一种方法:
(define (min4 a b c d)
(define (min2 x y)
(if (< x y) x y))
(min2 (min2 a b) (min2 c d)))
另一种方法,如果您不想使用内部函数:
Another way to do it, if you don't want to use an internal function:
(define (min4 a b c d)
(let ((min-ab (if (< a b) a b))
(min-cd (if (< c d) c d)))
(if (< min-ab min-cd) min-ab min-cd)))
这篇关于在 Scheme 中编写最小值过程的另一种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!