我是标准ML的新手并尝试编写以下代码
fun whilestat test stmt1 =
(fn x => if (test x) then (stmt1 x;whilestat test stmt1 ) else (x) );
Run Code Online (Sandbox Code Playgroud)
问题是它给了我以下错误
w.sml:21.6-22.82 Error: right-hand-side of clause doesn't agree with function result type [circularity]
expression: ('Z -> 'Y) -> 'Z -> 'Z
result type: ('Z -> 'Y) -> 'Z
in declaration:
whilestat2 = (fn arg => (fn <pat> => <exp>))
uncaught exception Error
raised at: ../compiler/TopLevel/interact/evalloop.sml:66.19-66.27
../compiler/TopLevel/interact/evalloop.sml:44.55
../compiler/TopLevel/interact/evalloop.sml:292.17-292.20
Run Code Online (Sandbox Code Playgroud)
我只是试图通过电子邮件发送一段时间,如果staement为真,那么它会递归,否则返回值.
问题在于返回类型whilestat.在then分支中,返回一个函数,而在else分支中,返回一个任意数据.我认为当你在then分支中进行递归时,你只是忘了传递所有的参数.
这是我写它的方式(注意也没有必要使用fn x => ...,我认为这有助于你的困惑).
fun whilestat test stmt1 x =
if test x
then (stmt1 x; whilestat test stmt1 x)
else x
Run Code Online (Sandbox Code Playgroud)
将来,您可能会发现在源代码中明确注释类型有用,可以仔细检查您的推理.我通过尝试填写???以下内容找到了您的错误:
fun whilestat (test : 'a -> bool) (stmt1 : 'a -> unit) : ??? =
...
Run Code Online (Sandbox Code Playgroud)