我正在尝试通过SICP学习计划.练习1.3内容如下:定义一个过程,该过程将三个数字作为参数,并返回两个较大数字的平方和.请评论我如何改进我的解决方案.
(define (big x y)
(if (> x y) x y))
(define (p a b c)
(cond ((> a b) (+ (square a) (square (big b c))))
(else (+ (square b) (square (big a c))))))
Run Code Online (Sandbox Code Playgroud)
小智 28
仅使用本书那一点提出的概念,我会这样做:
(define (square x) (* x x))
(define (sum-of-squares x y) (+ (square x) (square y)))
(define (min x y) (if (< x y) x y))
(define (max x y) (if (> x y) x y))
(define (sum-squares-2-biggest x y z)
(sum-of-squares (max x y) (max z (min x y))))
Run Code Online (Sandbox Code Playgroud)
Chr*_*ung 13
big被称为max.当它存在时使用标准库功能.
我的方法不同.我只需添加所有三个的正方形,然后减去最小的正方形,而不是大量的测试.
(define (exercise1.3 a b c)
(let ((smallest (min a b c))
(square (lambda (x) (* x x))))
(+ (square a) (square b) (square c) (- (square smallest)))))
Run Code Online (Sandbox Code Playgroud)
当然,无论您喜欢这种方法还是一堆if测试,都取决于您.
使用SRFI 95的替代实现:
(define (exercise1.3 . args)
(let ((sorted (sort! args >))
(square (lambda (x) (* x x))))
(+ (square (car sorted)) (square (cadr sorted)))))
Run Code Online (Sandbox Code Playgroud)
如上所述,但作为一个单行(感谢synx @ freenode #scheme); 还需要SRFI 1和SRFI 26:
(define (exercise1.3 . args)
(apply + (map! (cut expt <> 2) (take! (sort! args >) 2))))
Run Code Online (Sandbox Code Playgroud)
Bil*_*ard 10
我用下面的代码,它使用内置的做到了min,max和square程序.它们非常简单,只能使用文本中引入的内容.
(define (sum-of-highest-squares x y z)
(+ (square (max x y))
(square (max (min x y) z))))
Run Code Online (Sandbox Code Playgroud)
这样的事情怎么样?
(define (p a b c)
(if (> a b)
(if (> b c)
(+ (square a) (square b))
(+ (square a) (square c)))
(if (> a c)
(+ (square a) (square b))
(+ (square b) (square c)))))
Run Code Online (Sandbox Code Playgroud)
仅使用本文中介绍的概念,我认为这很重要,这里有一个不同的解决方案:
(define (smallest-of-three a b c)
(if (< a b)
(if (< a c) a c)
(if (< b c) b c)))
(define (square a)
(* a a))
(define (sum-of-squares-largest a b c)
(+ (square a)
(square b)
(square c)
(- (square (smallest-of-three a b c)))))
Run Code Online (Sandbox Code Playgroud)
小智 5
(define (sum-sqr x y)
(+ (square x) (square y)))
(define (sum-squares-2-of-3 x y z)
(cond ((and (<= x y) (<= x z)) (sum-sqr y z))
((and (<= y x) (<= y z)) (sum-sqr x z))
((and (<= z x) (<= z y)) (sum-sqr x y))))
Run Code Online (Sandbox Code Playgroud)
(define (f a b c)
(if (= a (min a b c))
(+ (* b b) (* c c))
(f b c a)))
Run Code Online (Sandbox Code Playgroud)
我觉得还不错,您有什么具体需要改进的地方吗?
你可以这样做:
(define (max2 . l)
(lambda ()
(let ((a (apply max l)))
(values a (apply max (remv a l))))))
(define (q a b c)
(call-with-values (max2 a b c)
(lambda (a b)
(+ (* a a) (* b b)))))
(define (skip-min . l)
(lambda ()
(apply values (remv (apply min l) l))))
(define (p a b c)
(call-with-values (skip-min a b c)
(lambda (a b)
(+ (* a a) (* b b)))))
Run Code Online (Sandbox Code Playgroud)
并且这个 (proc p) 可以很容易地转换为处理任意数量的参数。