Next: , Up: Samples   [Index]


1.4.1 Trivial Common Samples

aime programs are either procedural, either non procedural. In the former case, all code pertains some function. There are no nested functions. There is one main function. In the latter there are no functions defined.

The hello world program, as allowed by the standalone aime interpreter, non procedural:

o_text("Hello, World!\n");

The greatest common divisor, same aime standalone interpreter, for ‘a’ and ‘b’:

if (!a) {
    v_text("no can do\n");
} else {
    if (!b) {
	v_text("no can do\n");
    } else {
	integer v;

	while (1) {
	    a = a % b;
	    if (!a) {
		v = b;
		break;
	    } else {
		b = b % a;
		if (!b) {
		    v = a;
		    break;
		}
	    }
	}

	o_integer(v);
	o_byte('\n');
    }
}

may run as:

aime <FILE> integer a <VALUE> integer b <VALUE>

Generate some random numbers:

while (N) {
    N -= 1;
    o_integer(drand(MAX));
    o_byte('\n');
}

run program as:

aime <FILE> integer N <VALUE> integer MAX <VALUE>

Read numbers on standard input, one per line, sort them and write them on standard output:

integer
partition(list l, integer head, integer tail)
{
    integer call, pivot;

    pivot = l_q_integer(l, head);
    while (1) {
	while (l_q_integer(l, head) < pivot) {
	    head += 1;
	}
	while (l_q_integer(l, tail) > pivot) {
	    tail -= 1;
	}
	if (head < tail) {
	    l_spin(l, head, tail);
	    head += 1;
	    tail -= 1;
	} else {
	    call = tail;
	    break;
	}
    }

    return call;
}


void
quicksort(list l, integer head, integer tail)
{
    if (head < tail) {
	integer call;

	call = partition(l, head, tail);

	quicksort(l, head, call);
	quicksort(l, call + 1, tail);
    }
}


integer
main(void)
{
    file f;
    list l;
    integer i, n;
    text s;

    # open _f_ for reading
    f_affix(f, "/dev/stdin");

    # read lines, one at a time
    while (f_line(f, s) != -1) {
	# append to the _l_ list the numerical interpretation of _s_
	lb_p_integer(l, atoi(s));
    }

    # get the length of _l_
    n = l_length(l);

    # sort _l_ list
    quicksort(l, 0, n - 1);

    # print the numbers
    i = 0;
    while (i < n) {
	# print the number at _i_ index, with at least 16 characters
	o_form("/w16/\n", l[i]);
	i += 1;
    }

    return 0;
}

There is no need to check for errors - like file opening and number parsing errors, for if such errors occur they are trapped and the program execution terminated.

See Error Dispatching Samples.


Next: Error Dispatching Samples, Up: Samples   [Index]