4.2. "Hello world" program

This example program prints a personalized "Hello" message a given number of times. It demonstrates variable naming, function definitions and basic control structures, as well as command line arguments.

The program also shows the basic similarities between Gamma and the C language, and some important differences which highlight the power of Gamma.

#!/usr/cogent/bin/gamma

/* This function iterates, saying hello to the given name.
In Gamma, all functions return a value, which is the
result of the last evaluated expression in the function.
In this case, we return the string "ok".
*/

function say_hello (name, n)
{
    local i;

    for (i = 0; i < n; i++)
        princ ("Hello ", name, "\n");
        "ok";
}

/* A program may optionally have a function main()
declared, in which case Gamma will execute the
main() function after all of the program file has been
read in. If no main() declared, the programmer must
explicitly call a function or enter an event loop at
some point while reading the file. Any code which is not a
function definition will be automatically run AS THE FILE
IS READ. This is useful for providing feedback to the user
while loading.  */
		
function main ()
{
    /* Define some locally scoped variables. Notice that
    Gamma implements abstract data typing, so it is not
    necessary to declare the variable type.
    */

    local repeat = 1, my_name = "world";

    /* Access the command line arguments. argv is a list of the
    command line arguments, as strings, where the first argument
    is the program name.  */

    /* The second argument (cadr(argv)) is my_name,
    if present.
    */
			
    if (cadr(argv))
        my_name = cadr (argv);
			
    /* The third argument (caddr(argv)) is the number
    of iterations, if present.
    */

    if (caddr(argv))
        repeat = number (caddr(argv));

    /_now print the message */

    result = say_hello (my_name, repeat);
    princ (result, "\n");
}