Reputation: 81
I am solving problems from htdp.org. I would like to know in scheme which is a better practice to evaluate long expressions having a common operator like '+' or '*'.
Example :
> (* 1 10 10 2 4) ; Version A
> (* 1 (* 10 (* 10 (* 2 4)))) ; Version B
Should I follow A or B. Also I please consider the above example for algebraic expressions like surface area of cylinder.
-Abhi
Upvotes: 2
Views: 179
Reputation: 643
A bit of a followup on this. (* a b c ...)
is not necessarily equivalent to (* (* a b) ...)
when you're talking about timing.
Some implementations may recognize the common operation, but try timing these two definitions of factorial:
(define (f1 n)
(let loop ((up 2)
(down n)
(a 1))
(cond ((> up down) a)
((= up down) (* a up))
(else
(loop (+ 1 up) (- 1 down)
(* a up down))))))
(define (f2 n)
(let loop ((up 2)
(down n)
(a 1))
(cond ((> up down) a)
((= up down) (* a up))
(else
(loop (+ 1 up) (- 1 down)
(* a (* up down)))))))
The second procedure is considerably faster than the first for me.
Upvotes: 1
Reputation: 4018
The real question should be, do they produce different results? Let's try in our REPL:
>> (* 1 10 10 2 4)
800
>> (* 1 (* 10 (* 10 (* 2 4))))
800
>>
Since they're essentially the same (using your example), I'd opt for going with lower ceremony / noise in the code. Use the first one.
Upvotes: 7