使用 OCaml 输出一个简单的乘法 table

Using OCaml to output a simple multiplication table

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

乘法示例 table 如果函数参数为 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);;

稍后我在 table 函数中调用行,如下所示:

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

当我 运行 table "foo" 5 时,它只是挂起。另外,以后如何更好地处理这样的错误?有任何推荐的 OCaml 调试选项吗?

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

在第一种情况下,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

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