[racket] How to prevent code from running when `required`?

From: Neil Van Dyke (neil at neilvandyke.org)
Date: Thu Jun 2 19:44:10 EDT 2011

Rodolfo Carvalho wrote at 06/02/2011 05:42 PM:
> I would like a have a file that when run standalone executes some 
> code, and when "required" by another module just provides some 
> definitions.

The following works on Linux.  You might have to change the "/usr/bin" 
to be whatever directory your "racket" executable is in.

#!/usr/bin/racket -ucm
#lang racket/base

(define foo 42)

(define (bar x) (* x 2))

(define (main)
  (display "Hello, world!\n"))

(provide foo bar main)

If "-ucm" is difficult to remember, the "m" has to be last, but one can 
swap the order of the "u" and the "c", for a mnemonic that no student 
will forget.

Also, "-M" (uppercase) isn't yet used as a command line option, so that 
might be good shorthand to add for this kind of module/script.  Perhaps 
"-M" could permit the procedure name after, since requiring multiple 
modules providing "main" would be a pain outweighing the convenience, 
IMHO.  I think it would require a low-level change to the command-line 
parser (since"#!" wants to read only a single argument).


Posted on the users mailing list.