我正试着通过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))))))发布于 2008-10-02 10:26:13
在我看来还可以,你有什么特别需要改进的地方吗?
你可以这样做:
(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)))))这个函数(proc p)可以很容易地转换为处理任意数量的参数。
发布于 2009-07-21 21:18:43
仅使用本书中介绍的概念,我就会这样做:
(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))))发布于 2008-10-02 10:27:56
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)))))当然,您是更喜欢这种方法,还是喜欢一堆if测试,这取决于您。
使用SRFI 95的替代实现
(define (exercise1.3 . args)
(let ((sorted (sort! args >))
(square (lambda (x) (* x x))))
(+ (square (car sorted)) (square (cadr sorted)))))如上所述,但作为一行程序(感谢synx @ freenode #方案);还需要SRFI 1和SRFI 26
(define (exercise1.3 . args)
(apply + (map! (cut expt <> 2) (take! (sort! args >) 2))))https://stackoverflow.com/questions/161666
复制相似问题