Exercise 4.52: Implement a new construct called
if-fail that permits the user to catch the failure of an expression.
If-fail takes two expressions. It evaluates the first expression as
usual and returns as usual if the evaluation succeeds. If the evaluation
fails, however, the value of the second expression is returned, as in the
following example:
;;; Amb-Eval input:
(if-fail
(let ((x (an-element-of '(1 3 5))))
(require (even? x))
x)
'all-odd)
;;; Starting a new problem
;;; Amb-Eval value:
all-odd
;;; Amb-Eval input:
(if-fail
(let ((x (an-element-of '(1 3 5 8))))
(require (even? x))
x)
'all-odd)
;;; Starting a new problem
;;; Amb-Eval value:
8
练习 4.52:实现一种新的构造形式,称为 if-fail,它允许用户捕获表达式的失败。if-fail 接受两个表达式:照常对第一个表达式求值,若求值成功则照常返回其值;然而,若求值失败,则返回第二个表达式的值,如下例所示:
;;; Amb-Eval input:
(if-fail
(let ((x (an-element-of '(1 3 5))))
(require (even? x))
x)
'all-odd)
;;; Starting a new problem
;;; Amb-Eval value:
all-odd
;;; Amb-Eval input:
(if-fail
(let ((x (an-element-of '(1 3 5 8))))
(require (even? x))
x)
'all-odd)
;;; Starting a new problem
;;; Amb-Eval value:
8
;;; Amb-Eval input:
(if-fail
(let ((x (an-element-of '(1 3 5))))
(require (even? x))
x)
'all-odd)
;;; Starting a new problem
;;; Amb-Eval value:
all-odd
;;; Amb-Eval input:
(if-fail
(let ((x (an-element-of '(1 3 5 8))))
(require (even? x))
x)
'all-odd)
;;; Starting a new problem
;;; Amb-Eval value:
8