(let echo-server () ;; create a TCP server (define-values (in out) (tcp-accept listener)) ;; handle an incoming connection in a (green) thread (thread (λ () (copy-port in out) (close-output-port out))) ;; and immediately loop back to accept additional clients (echo-server)) The combination of dynamic compilation and a rich system interface makes Racket a capable scripting language, similar to Perl or Python. The following example demonstrates walking a directory tree, starting at the current directory. It uses the in-directory function to construct a sequence that walks the tree. The for form binds path to each path in the sequence, and regexp-match? tests these paths against the given regexp pattern. #lang racket ;; Finds Racket sources in all subdirs (for ([path (in-directory)]) ; iterate over the current tree (when (regexp-match? #rx"[.]rkt$" path) (printf "source file: ~a\n" path))) The next example uses a hash table to record previously seen lines and print only unique ones. #lang racket ;; Report each unique line from stdin (let ([saw (make-hash)]) (for ([line (in-lines)]) (unless (hash-ref saw line #f) (displayln line)) (hash-set! saw line #t))) Both of these programs can be run in DrRacket, or on the command line, via the racket executable. Racket ignores an initial shebang line, making it possible to turn such programs to executable scripts. The following script demonstrates this, in addition to using Racket's library for command-line argument parsing: #!/usr/bin/env racket #lang racket (command-line #:args (base-dir ext re) (for ([p (in-directory)] #:when (regexp-match? (string-append "[.]" ext "$") p) [(line num) (in-indexed (file->lines p))]) (when (regexp-match? (pregexp re) line) (printf "~a:~a: ~a~n" p (+ num 1) line)))) The script is a grep-like utility, expecting three command-line arguments: a base directory, a filename extension, and a (perl-compatible) regular expression. It scans the base directory for files with the given suffix, and print lines matching the regexp pattern. Resource management and sandboxing Racket features the concept of a "custodian": a kind of value that acts as a resource manager. This is often used in network servers, where each connection is dealt with in a new custodian, making it easy to "clean-up" all resources that might have been left open by the handler (e.g., open ports). The following extends the "echo server" example with such a custodian use: #lang racket (define listener (tcp-listen 12345)) ;; per-connection handler (define (handler in out) (copy-port in out) (close-output-port out)) (let echo-server () (define-values (in out) (tcp-accept listener)) (thread (λ