SML递归调用函数

时间:2013-11-27 22:25:51

标签: sml

我正在尝试在SML中实现递归调用函数。我的代码是

CM.make "$cml/cml.cm";
open CML;
fun sender n()= if (n<100)
then 
(
TextIO.print (Int.toString(n)^"\n");
sender n+1
)
else
exit ()

fun main () = let
    val _ = spawn (sender 3);
    val tid1 = getTid();
in
    TextIO.print("MY TID" ^ (tidToString tid1)^"\n")
end;
RunCML.doit(main, NONE);

我收到以下错误

Cml.sml:3.5-10.8 Error: right-hand-side of clause doesn't agree with function result type [circularity] expression: unit -> 'Z result type: 'Z in declaration: sender = (fn arg => (fn <pat> => <exp>))

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的功能sender

开头
fun sender n()= ...

给它类型

sender : int -> unit -> 'a

您需要main中的定义。但是,当您稍后以递归方式调用它时,将其称为

sender n+1

现在,即使你把它写成

sender (n+1)

要获得正确的优先级,您仍然可以获得类型unit -> 'a,而您需要类型'a。所以你需要做的就是向它传递额外的() : unit,并且你的sender函数将进行类型检查:

fun sender n () =
    if (n<100)
    then (
        TextIO.print (Int.toString(n)^"\n");
        sender n+1 ())
    else exit ()
相关问题