|
|
|
|
|
by guicho271828
3269 days ago
|
|
As an interesting example, conditions and restarts can be used to implement an interactive system that is composable with other programs. For instance, you can implement a simple y/n question handler as follows: (defun fn1 ()
(if (yes-or-no-p) (print :yes) (print :no)))
(defun fn2 ()
(fn1))
[yes-or-no-p](http://clhs.lisp.se/Body/f_y_or_n.htm) is an interactive function that reads from the stdin. However, you cannot programatically answer "yes" to fn1, as other functions in the call stack (fn2) has no way to know that fn1 halts because it waits for the input from the stdin. Instead, a condition system allows this: (defun fn1 ()
(restart-case (error "yes or no?")
(yes () (print :yes))
(no () (print :no))))
(defun fn2-interactive ()
(fn1))
(defun fn2-automated ()
(hander-bind ((error (lambda (c) (invoke-restart 'yes)))) ;; handler
(fn1)))
When you call fn2-automated, an error is signaled, handled by the handler, which invokes a restart 'yes, then :yes is printed. Interactivity is still maintained by fn2-interactive. |
|