我是标准ML的新手并尝试编写以下代码
fun whilestat test stmt1 =
(fn x => if (test x) then (stmt1 x;whilestat test stmt1 ) else (x) );
问题是它给了我以下错误
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
我只是试图通过电子邮件发送一段时间,如果staement为true,那么它会递归,否则返回值。
答案 0 :(得分:7)
问题在于whilestat
的返回类型。在then
分支中,返回一个函数,而在else
分支中,返回一个任意数据。当你在then
分支中进行递归时,我想你只是忘了传递所有的参数。
以下是我的写作方式(另请注意,我认为没有必要使用fn x => ...
,我认为这会导致您的混淆)。
fun whilestat test stmt1 x =
if test x
then (stmt1 x; whilestat test stmt1 x)
else x
将来,您可能会发现在源代码中明确注释类型有用,可以仔细检查您的推理。我通过尝试填写下面的???
找到了您的错误:
fun whilestat (test : 'a -> bool) (stmt1 : 'a -> unit) : ??? =
...