3
(define (sum-two-sqrt a b c)

    (cond ((and (<= c a) (<= c b)) sqrt-sum(a b))
           ((and (<= a b) (<= a c)) sqrt-sum(b c))
           ((and (<= b a) (<= b c)) sqrt-sum(a c))
    )
)
(define (sqrt-sum x y)
           (+ (* x x) (*y y))
)
(define (<= x y)
      (not (> x y))

(sum-two-sqrt 3 4 5)

这是我的代码

请帮我解决问题。:)

我今天才开始学习 Lisp。

之前学过一些C,但是这两种语言完全不同!

这就是问题定义一个以三个数字作为参数并返回两个较大数字的平方和的过程。

如果你有更好的算法

发表它!

谢谢 :)

4

4 回答 4

3

无需定义<=,这是一个原始操作。修正几个错别字后:

  • sqrt-sum:您错误地调用了该程序;左括号必须写过程名称之前,而不是之后
  • sqrt-sum:(*y y)不正确,你肯定是说(* y y); 运算符后的空格。

这应该有效:

(define (sqrt-sum x y)
  (+ (* x x) (* y y)))

(define (sum-two-sqrt a b c)
  (cond ((and (<= c a) (<= c b)) (sqrt-sum a b))
        ((and (<= a b) (<= a c)) (sqrt-sum b c))
        ((and (<= b a) (<= b c)) (sqrt-sum a c))))

或另一种选择:

(define (sum-two-sqrt a b c)
  (let ((m (min a b c)))
    (cond ((= a m) (sqrt-sum b c))
          ((= b m) (sqrt-sum a c))
          (else (sqrt-sum a b)))))
于 2012-09-13T05:00:27.080 回答
1

遵循@J.Spiral 的建议并得到@River 的支持,以下 Racket 代码对我来说很好读:

#lang racket

(define (squares-of-larger l)
  (define two-larger (remove (apply min l) l))
  (for/sum ([i two-larger]) (* i i)))

(squares-of-larger '(3 1 4)) ;; should be 25

请注意,这个解决方案是完全可用的,因为“删除”只是返回一个新列表。

另请注意,这甚至与 HtDP 不在同一个社区;我只是想简洁地表达这一点,并炫耀for/sum。

于 2012-09-13T05:20:50.550 回答
0

我这里没有 Scheme 解释器,但下面似乎比其他建议短:) 所以它在 CL 中,但在 Scheme 中应该看起来非常相似。

(defun sum-two-sqrt (a b c)
  (let ((a (max a b))
        (b (max (min a b) c)))
    (+ (* a a) (* b b))))

在 Scheme 中,这将转化为:

(define (sum-two-sqrt a b c)
  (let ((a (max a b))
        (b (max (min a b) c)))
    (+ (* a a) (* b b))))
于 2012-09-13T09:41:19.997 回答
0

该算法似乎有效,只需转动

*y

* y

空格在这里很重要,否则您是在告诉解释器您要使用该功能*y

在之后添加一个右括号

(define (<= x y) (not (> x y))

sqrt-sum(a b) 

转向

(sqrt-sum a b)

其他 sqrt-sum 调用也是如此

编辑:也是一种可能性:

(define (square a) (* a a))
(define (square-sum a b c)
    (- (+ (square a) 
          (square b)
          (square c))
       (square (min a b c))))
于 2012-09-13T05:04:06.940 回答