Skip to content

Instantly share code, notes, and snippets.

@alxbnct
Last active May 27, 2022 02:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxbnct/ae8f38157e970d214e9bd59e58aa2a92 to your computer and use it in GitHub Desktop.
Save alxbnct/ae8f38157e970d214e9bd59e58aa2a92 to your computer and use it in GitHub Desktop.
Macro for printing variables in scheme

Very often we want to debug a program by printing variables, the following macro makes it easier and more convenient.

(define-syntax dbg
  (syntax-rules ()
    ((_ fst ...)
     (begin (let loop ((lst (list fst ...))
                       (symbol-names (map symbol->string (quote (fst ...)))))
              (if (not (null? lst))
                  (begin (display (string-append " " (car symbol-names) ": "))
                         (display (car lst))
                         (display ",\t")
                         ;; when it's the last element of the list,
                         ;; print a newline
                         (if (null? (cdr lst)) (newline))
                         (loop (cdr lst) (cdr symbol-names)))))))))

How to use it?

Suppose we want to print out variables var1, we can do (dbg var1). we can also print multiple variables with (dbg var1 var2 var3). See the following example.

(define (my-sqrt x)
  (define (good-enough? guess previous-guess)
    (< (abs (- guess previous-guess)) 0.0001))
  (define (average x y)
    (/ (+ x y) 2))
  (define (improve guess x)
    (average guess (/ x guess)))
  (define (sqrt-iter guess previous-guess x iter)
    (dbg iter guess)
    (if (good-enough? guess previous-guess)
        guess
        (sqrt-iter (improve guess x) guess x (1+ iter))))
  (sqrt-iter 1.0 -1 x 1))

And (in MIT/GNU scheme) evaluate (my-sqrt 42) yields

 iter: 1,	 guess: 1.,	
 iter: 2,	 guess: 21.5,	
 iter: 3,	 guess: 11.726744186046512,	
 iter: 4,	 guess: 7.654150476761481,	
 iter: 5,	 guess: 6.570684743283659,	
 iter: 6,	 guess: 6.481356306333419,	
 iter: 7,	 guess: 6.480740727643494,	
 iter: 8,	 guess: 6.48074069840786,	
;Value: 6.48074069840786
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment