views:

639

answers:

2

I wrote this scheme code to compute one solution of the quadratic equation a*x2 + b*x + c = 0

(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a)))

However, someone told me that this procedure is hard to understand. Why?

What would a cleaned up version of this procedure look like? Please let me know why the new procedure would be easier to understand.

Thanks

+2  A: 

Well, one reason is that it's all on one line. You can make it more readable using something called pretty-printing, where you break it up into multiple lines and use whitespace:

(define (solve-quadratic-equation a b c)
  (define disc (sqrt (- (* b b)
                        (* 4.0 a c))))
  (/ (+ (- b) disc)
     (* 2.0 a)))

This way you can more clearly see the structure of the expressions.

And here's a quote from SICP:

There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as

(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))

which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form

(+ (* 3
      (+ (* 2 4)
         (+ 3 5)))
   (+ (- 10 7)
      6))

following a formatting convention known as pretty-printing, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.

yjerem
A: 

Isn't scheme all about developing a language to solve a problem? I admit I don't know much scheme, but I would add some indentation and add a square definelike so.

 (define (solve-quadratic-equation a b c)
     (define square (x) (* x x) 
     (define disc (sqrt (- (square b) (* 4.0 a c)))) 
                        (/ (+ (- b) disc) (* 2.0 a))))
Nick Stinemates