Iota matrix multiply example

mmm.im:

// Matrix-matrix multiply

uses io.print, io.printi, conv.stoi, conv.itos

// A is m-by-n, B is n-by-p, result is m-by-p
// Arrays are stored as arrays of rows, i.e., A is an array of m n-vectors.
mmm(A: array[array[int]], B: array[array[int]]): array[array[int]] = (
    i:int;
    j:int;
    k:int;

    m: int = length(A);
    n: int = length(B);

    if (!(m > 0)) return empty_array_();
    if (!(n > 0)) return empty_array_();

    p: int = length(B[0]);

    // Check that A is the correct size.
    i = 0;
    while (i < m) (
	if (!(n == length(A[i]))) return empty_array_();
	i = i + 1
    );
    
    // Check that B is the correct size.
    while (i < n) (
	if (!(p == length(B[i]))) return empty_array_();
	i = i + 1
    );

    // Allocate a new array.
    C: array[array[int]] = new array[int][m](new int[p](0));

    // MMM
    i = 0;
    while (i < m) (
	j = 0;
	while (j < n) (
	    k = 0;
	    while (k < p) (
		C[i][k] = C[i][k] + A[i][j] * B[j][k];
		k = k + 1
	    );
	    j = j + 1
	);
	i = i + 1
    );

    C
)


// the "empty 2D-array" serves a similar purpose
// as "null" from Iota+
empty_array_():array[array[int]] =
        new array[int][0]( new int[0](0) )


main(args: array[string]): int = (
    if (length args < 3) (
	print("Usage: mmm <m> <n> <p>\n");
	return 1;
    )

    m: int = stoi(args[0], 1);
    n: int = stoi(args[1], 1);
    p: int = stoi(args[2], 1);

    A: array[array[int]] = new array[int][m](new int[n](0));
    B: array[array[int]] = new array[int][n](new int[p](0));

    i: int;
    j: int;

    i = 0;
    while (i < m & i < n) (
	A[i][i] = 1;
	i = i + 1
    );

    i = 0;
    while (i < n) (
	j = 0;
	while (j < p) (
	    B[i][j] = i * j;
	    j = j + 1
	);
	i = i + 1
    );

    C: array[array[int]] = mmm(A, B);

    i = 0;
    while (i < m) (
	j = 0;
	while (j < n) (
	    print("A[" + itos(i) + "][" + itos(j) + "] = "
			    + itos(A[i][j]) + "\N");
	    j = j + 1
	);
	i = i + 1
    );

    i = 0;
    while (i < n) (
	j = 0;
	while (j < p) (
	    print("B[" + itos(i) + "][" + itos(j) + "] = "
			    + itos(B[i][j]) + "\N");
	    j = j + 1
	);
	i = i + 1
    );

    i = 0;
    while (i < m) (
	j = 0;
	while (j < p) (
	    print("C[" + itos(i) + "][" + itos(j) + "] = "
			    + itos(C[i][j]) + "\N");
	    j = j + 1
	);
	i = i + 1
    );

    0
)