Roger Ko
Roger Ko

Reputation: 197

Using OCaml to output a simple multiplication table

I'm trying to create a simple function that can write output to a file, say file.txt. The output is a multiplication table (as seen below).

Example of the multiplication table if the function argument is 5: Example of the multiplication table if the function argument is 5

The problem is that OCaml just hangs when I run the code (probably because of an infinite recursion?). I keep looking through the logic and it seems okay..

(*n is the row counter and n2 is the column counter*)
let rec row ch x n =
    let rec column ch x n n2 =
        (*If column counter reaches limit then stop here*)
        if (n2 = x+1)
        then ()
        else
            output_string ch (string_of_int (n2*n));
            output_char ch '\t';
            column ch x n (n2+1)
    in
        column ch x n 1;

        (*If row counter reaches limit then stop here*)
        if n = x+1
        then ()
        else
            output_char ch '\n';
            row ch x (n+1);;

Later I call row in table function like this:

let rec table file x =
    let ch = open_out file in
        row ch x 1;
        close_out ch;;

When I run table "foo" 5, it just hangs. Also, in the future, how can I better handle errors like this? Any recommended debugging options for OCaml?

Upvotes: 1

Views: 247

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

You have two cases of the same problem: the else part of if/then/else controls just one expression but you're expecting it to control several expressions.

In the first case, the else is just controlling the output_string. This means that the rest of the column function is going to be executed in all cases. This is, in fact, an infinite recursion.

In the second case the else just controls the output_char. Again, this gives you an infinite recursion.

You can fix this by adding begin/end here:

begin
output_string ch (string_of_int (n2*n));
output_char ch '\t';
column ch x n (n2+1)
end

And here:

begin
output_char ch '\n'; row ch x (n+1)
end

After I make these changes, the code works for me.

Upvotes: 3

Related Questions