【问题标题】:Error: this expression has type unit but an expression was expected of type int错误:此表达式的类型为 unit,但预期的表达式为 int 类型
【发布时间】:2021-04-08 17:27:03
【问题描述】:

我正在尝试执行这个简单的 while 循环,但它不起作用。它给了我以下错误:

此表达式具有单元类型,但表达式应为类型 诠释

let function () = 
  let current = ref 0 in
  let square = ref !current in
  while(((square := !current * !current) mod 1000000) != 269696) do
    current := !current +1
  done;
  !square
;;

【问题讨论】:

  • current := !current +1; : 你必须在一个单元指令之后放一个分号
  • @Butanium 不在 OCaml 中。分号分隔两个单元指令。如果没有说明,就不需要放一个。
  • 哦,是的,我的错是因为分号缺少 x)。无论如何感谢您纠正我!

标签: syntax-error ocaml


【解决方案1】:

首先,function 是 OCaml 中的一个关键字,你不能用它来命名你的函数。 此外,while 循环中的条件是错误的: 这个square := !current * !current 是一个赋值,它的类型是unit。将其用作mod 的参数是类型错误,该参数需要两个整数作为输入。

您可能应该在循环内进行分配,并且只在循环条件下测试!square mod 1000000 <> 269696。 请注意,我使用了<> 结构不等式,而不是物理上的不等式!=,幸运的是它对整数做了同样的事情,但除非你知道这一点,否则你不应该使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多