guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

condition-case


From: Thien-Thi Nguyen
Subject: condition-case
Date: Fri, 20 Nov 2009 12:09:25 +0100
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1.50 (gnu/linux)

Here is an implementation of the Emacs Lisp `condition-case',
along with a small test harness:

(define-macro (condition-case var bodyform . handlers)
  `(catch
    #t (lambda ()
         ,bodyform)
    (lambda ,var
      (case (car ,var)
        ,@(map (lambda (h)
                 ;; Emacs Lisp `case' handles lone symbols,
                 ;; which is pleasant.
                 `(,(let ((name (car h)))
                      (if (or (eq? 'else name) (pair? name))
                          name
                          (list name)))
                   ,@(cdr h)))
               handlers)
        ,@(if (assq 'else handlers)
              '()
              `((else
                 ;; This copy is to workaround a (possibly misguided)
                 ;; `nconc2last' used in the Guile 1.4.x implementation.
                 (let ((copy (list-copy ,var)))
                   (apply throw (car copy) (cdr copy))))))))))

;;; (put 'condition-case 'scheme-indent-function 2)

(define (read-string s)
  (call-with-input-string s read))

(write-line
 (condition-case c
     (if (pair? (cdr (command-line)))
         (apply throw (map read-string (cdr (command-line))))
         'ok)
   (bad
    (simple-format #t "BAD: ~S !~%" (cdr c))
    42)
   ((a b c)
    (write c) (newline)
    (cdr c))
   (else
    (let ((key (car c))
          (args (cdr c)))
      (write-line "ELSE!")
      (write key) (newline)
      (write args) (newline)
      'else))))
To play, save to (say) /tmp/z.scm, and invoke from command line, e.g.:
  guile -s /tmp/z.scm
  guile -s /tmp/z.scm bad stuff happens
  guile -s /tmp/z.scm no bad stuff happens

I wonder if there is a better way, where better means "more idiomatic"
or "standardardized", or "more elegant", or what have you.

thi

reply via email to

[Prev in Thread] Current Thread [Next in Thread]