使用OCaml输出简单的乘法表

时间:2016-07-03 04:20:41

标签: ocaml

我试图创建一个可以将输出写入文件的简单函数,比如file.txt。输出是一个乘法表(如下所示)。

如果函数参数为5,乘法表的示例: Example of the multiplication table if the function argument is 5

问题是当我运行代码时OCaml会挂起(可能是因为无限递归?)。我一直在查看逻辑,看起来没问题。

(*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);;

后来我在表函数中调用了这样的行:

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

当我运行table "foo" 5时,它就会挂起。此外,将来,我怎样才能更好地处理这样的错误? OCaml的任何推荐调试选项?

1 个答案:

答案 0 :(得分:3)

您有两个相同问题的案例:else if/then/else部分只控制一个表达式,但您希望它能控制多个表达式。

在第一种情况下,else只是控制output_string。这意味着column函数的其余部分将在所有情况下执行。事实上,这是一次无限递归。

在第二种情况下,else只控制output_char。再次,这给你一个无限的递归。

您可以在此处添加begin/end来解决此问题:

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

在这里:

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

进行这些更改后,代码对我有效。

相关问题