Tuesday, June 19, 2007

Scheme Example: adding a debugging keyword

The topic came up on SISC users of how to add a debug keyword to the language. That is, a keyword, that when hit, will stop execution and allow you to inspect various variables.

The solution was then provided. I've tweaked that solution ever so slightly and ended up with:

 (define-syntax break
  (syntax-rules ()
    ((_ default-value (var ...))
     (begin
       (display (format "Debugging. Available lexical bindings: ~a\n" '(var ...)))
       (let ((child-env (make-child-environment (interaction-environment))))
         (putprop 'var child-env var) ...
         (let ((result (with-environment child-env (lambda () (repl)))))
           (display "Debugging ended.\n")
           (if (void? result) default-value result)))))

    ((_ var ...)
     (break => #f (var ...)))))

This new syntax is used like so:


(define (foo x)
  (let ((y (sqrt x)))
    (break x y) ; pause to look at x and y
    (/ x y)))

(define (bar x)
  (let ((y (sqrt x)))
    ; inspect x and y, return back y if you leave
    ; the repl by saying (exit). Otherwise, return
    ; value sent to exit - i.e. - (exit 100), returns 100.
    (/ x (break y (x y))))

I think this is so incredibly cool. In 13 lines of code I've added a debugging construct to the language that wasn't there before. How much Java would I had to write to support this? Even if I had wrestled with JPDA, how cleanly integrated would the resulting infrastructure be?

I suppose there are two ways to look at this: (1) What the?! Scheme doesn't even offer a debugger for the language. Or (2), Wow! You can really enhance Scheme easily. I suppose I'm focused on (2).

Thanks to Dominique Boucher who also highlighted this construct.

2 comments:

  1. Anonymous10:02 AM

    You are causing me to have such bad falshbacks to my Lisp class in college.
    I think there are two types of people. Those that have higher brain programming functions and those who don't. The higher brain guys love programming in things like Lisp which makes no conceptual or syntactical sense to the lower brained people.

    Now Python....there's real fun!!

    ReplyDelete
  2. Clearly there's a big leap between thinking that Lisp code is something other than a mess of parens.

    But, once you make that leap...the world of programming takes on a new shape :-).

    C'mon, take the red pill.

    ReplyDelete