Reputation: 15
I figured out how to use if statements in scheme, but not quite sure of how to use cond here. I need to change both if to cond. Any suggestions?
(define (pi err)
(let loop ([n 0]
[p +nan.0]
[c 0.0])
(if (< (abs (- c p)) (/ err 4))
(* 4 p)
(loop (add1 n)
c
((if (even? n) + -) c (/ 1 (+ 1 n n)))))))
Upvotes: 0
Views: 259
Reputation: 48775
With only one predicate and a then and else expression you won't get any benefits of converting it to a cond
, but it is very easy:
(if predicate-expression
then-expression
else-expression)
is the same as:
(cond
(predicate-expression then-expression)
(else else-expression))
Using your if
example it becomes:
(cond
((< (abs (- c p)) (/ err 4)) (* 4 p))
(else (loop ...)))
It's much more interesting if you have nested if like this:
(if predicate-expression
then-expression
(if predicate2-expression
then2-expression
else-expression))
which turns flatter and usually easier:
(cond
(predicate-expression then-expression)
(predicat2e-expression then2-expression)
(else else-expression))
Upvotes: 1