Last active
August 10, 2025 12:59
-
-
Save dandrake/5acca18cba90f87ff21f6ff012ef5f4f to your computer and use it in GitHub Desktop.
Parameters in Racket for debug-printing in recursive functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
#| | |
I'm trying to understand parameters in Racket. | |
One idea: for a recursive function, | |
have a parameter that says how much to indent a debugging print | |
statement so that I can see the call stack more clearly. | |
https://beautifulracket.com/explainer/parameters.html | |
https://www.greghendershott.com/2013/04/parameters-in-racket.html | |
|# | |
(define current-indent-level (make-parameter 0)) | |
(define current-print-debug? (make-parameter #f)) | |
(define (indentation n) | |
(string-join (build-list n (λ (_) " ")) "")) | |
(define (debug-printf . args) | |
(when (current-print-debug?) | |
(printf (string-join (list (indentation (current-indent-level)) | |
(apply format args)))))) | |
(define (fib n) | |
(debug-printf "fib called ~s\n" n) | |
(cond [(or (equal? n 0) (equal? n 1)) | |
n] | |
[else | |
(begin | |
(parameterize ([current-indent-level (add1 (current-indent-level))]) | |
(+ (fib (- n 1)) (fib (- n 2)))))])) | |
#| | |
Nicest way to change a parameter for some scope is parameterize: | |
(parameterize ([current-print-debug? #t]) | |
(fib 4)) | |
Or just change it globally: | |
(current-print-debug? #t) | |
...which is roughly the equivalent of this thing I do in Python: | |
DEBUG=True | |
... | |
if DEBUG: print("blah") | |
and I toggle the global variable. | |
|# | |
(current-print-debug? #t) | |
(fib 4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment