I find myself often wanting to examine statements and print what's going on there. For example, using this basic example:
(define (example-debug lst)
(if (null? lst)
'()
(example-debug (cdr lst))))
(example-debug '(1 2 3))
How could I put displays in both parts of the if
statement? Using python as an example, I might have something like this:
def example_debug(lst):
if not lst:
print ("End of list reached")
else:
print ("Element is: %s" % lst[0])
example_debug(lst[1:])
Is there a clean-ish or similar way to do that on the above in scheme? How are non-trivial programs usually 'debugged'?
An if
will be cumbersome to debug with print statements, because you can't write more than one expression for the consequent or the alternative, forcing you to use begin
if you want to do more than one thing (I'm using printf
which is specific to Racket, adjust to your interpreter):
(define (example-debug lst)
(if (null? lst)
(begin
(printf "End of list reached~n")
'()) ; this proc always returns '(), not very useful!
(begin
(printf "Element is: ~a~n" (first lst))
(example-debug (cdr lst)))))
It'll be slightly more readable with a cond
, which has implicit begin
s:
(define (example-debug lst)
(cond ((null? lst)
(printf "End of list reached~n")
'())
(else
(printf "Element is: ~a~n" (first lst))
(example-debug (cdr lst)))))
But to really answer your question: don't use prints to debug :). A good IDE (say, Racket) has a built-in debugger.