方案中的 if 和 cond
if and cond in scheme
我想出了如何在方案中使用 if 语句,但不太确定如何在这里使用 cond。如果要条件,我需要同时更改两者。有什么建议吗?
(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)))))))
只有一个谓词和一个 then 和 else 表达式,将它转换为 cond
不会有任何好处,但这非常简单:
(if predicate-expression
then-expression
else-expression)
等同于:
(cond
(predicate-expression then-expression)
(else else-expression))
使用您的 if
示例,它变为:
(cond
((< (abs (- c p)) (/ err 4)) (* 4 p))
(else (loop ...)))
如果像这样嵌套就更有趣了:
(if predicate-expression
then-expression
(if predicate2-expression
then2-expression
else-expression))
这变得更平坦,通常更容易:
(cond
(predicate-expression then-expression)
(predicat2e-expression then2-expression)
(else else-expression))
我想出了如何在方案中使用 if 语句,但不太确定如何在这里使用 cond。如果要条件,我需要同时更改两者。有什么建议吗?
(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)))))))
只有一个谓词和一个 then 和 else 表达式,将它转换为 cond
不会有任何好处,但这非常简单:
(if predicate-expression
then-expression
else-expression)
等同于:
(cond
(predicate-expression then-expression)
(else else-expression))
使用您的 if
示例,它变为:
(cond
((< (abs (- c p)) (/ err 4)) (* 4 p))
(else (loop ...)))
如果像这样嵌套就更有趣了:
(if predicate-expression
then-expression
(if predicate2-expression
then2-expression
else-expression))
这变得更平坦,通常更容易:
(cond
(predicate-expression then-expression)
(predicat2e-expression then2-expression)
(else else-expression))