Prev Up Next

We will now create a Scheme script that says hello to the world. Saying hello is of course not a demanding scripting problem for traditional scripting languages. However, understanding how to transcribe it into Scheme will launch us on the path to more ambitious scripts. First, a conventional Unix hello script is a file, with contents that look like:

echo Hello, World!

It uses the shell command echo. The script can be named hello, made into an executable by doing

chmod +x hello

and placed in one of the directories named in the PATH environment variable. Thereafter, anytime one types

hello

at the shell prompt, one promptly gets the insufferable greeting.

A Scheme hello script will perform the same output using Scheme (using the program in sec 1), but we need something in the file to inform the operating system that it needs to construe the commands in the file as Scheme, and not as its default script language. The Scheme script file, also called hello, looks like:

":"; exec mzscheme -r $0 "$@"

(display "Hello, World!")
(newline))

Everything following the first line is straight Scheme. However, the first line is the magic that makes this into a script. When the user types hello at the Unix prompt, Unix will read the file as a regular script. The first thing it sees is the ":", which is a shell no-op. The ; is the shell command separator. The next shell command is the exec. exec tells Unix to abandon the current script and run mzscheme -r $0 "$@" instead, where the parameter $0 will be replaced by the name of the script, and the parameter "$@" will be replaced by the list of arguments given by the user to the script. (In this case, there are no such arguments.)

We have now, in effect, transformed the hello shell command into a different shell command, viz,

mzscheme -r /whereveritis/hello

where /whereveritis/hello is the pathname of hello.

mzscheme calls the MzScheme executable. The -r option tells it to load the immediately following argument as a Scheme file after collecting any succeeding arguments into a vector called argv. (In this example, argv will be the null vector.)

Thus, the Scheme script will be run as a Scheme file, and the Scheme forms in the file will have access to the script's original arguments via the vector argv.

Now, Scheme has to tackle the first line in the script, which as we've already seen, was really a well-formed, traditional shell script. The ":" is a self-evaluating string in Scheme and thus harmless. The `;' marks a Scheme comment, and so the exec ... is safely ignored. The rest of the file is of course straight Scheme, and the expressions therein are evaluated in sequence. After all of them have been evaluated, Scheme will exit.

In sum, typing hello at the shell prompt will produce

Hello, World!

and return you to the shell prompt.

Prev Up Next