Error: this expression has type unit but an expression was expected of type int

Error: this expression has type unit but an expression was expected of type int

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

this expression has type unit but an expression was expected of type int

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
;;

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

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