syntax-error - 标准机器学习语法

标签 syntax-error sml

我是 Standard 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

我只是想模拟一个 while 条件,如果状态为真则递归,否则返回值。

最佳答案

问题出在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) : ??? =
  ...

关于syntax-error - 标准机器学习语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47537533/

相关文章:

MySQL 错误 1064 单列表

heroku - 在heroku上运行 “webpack --mode production”时出现语法错误

Python3 与 asyncpg 的语法错误

haskell - Haskell : Syntax error in input (unexpected `=' )

pattern-matching - 对 SML 中的两个分数求和

SML/NJ - 使用foldr 的一行长度函数

pattern-matching - SML 模式匹配抛出 "types of rules don' t 同意 [tycon 不匹配]"错误

python - 为什么我的程序会被注释干扰?

functional-programming - SML/NJ 中的环路

list - 打印列表中最大数字的长度时出现 SML 错误