Ocaml未绑定值

Ocaml未绑定值,ocaml,Ocaml,我正在尝试编写一个简单的Ocaml函数,但遇到以下错误: 错误:此表达式的类型为unit 但表达式应为int类型 let rec euclid a b = if a = b then a else if a < b then 1 else if a > b then 2 让rec euclid a b= 如果a=b,则a 否则,如果ab,则为2 要解决眼前的问题,您需要函数中的else子句: let rec euclid a b = if a = b then a

我正在尝试编写一个简单的Ocaml函数,但遇到以下错误:

错误:此表达式的类型为unit 但表达式应为int类型

let rec euclid a b = 
  if a = b then a
  else if a < b then 1
  else if a > b then 2
让rec euclid a b=
如果a=b,则a
否则,如果ab,则为2

要解决眼前的问题,您需要函数中的
else
子句:

let rec euclid a b =
  if a = b then a
  else if a < b then 1
  else 2 (* You know a > b is the only possible alternative *)
让rec euclid a b=
如果a=b,则a
否则,如果ab是唯一可能的选择*)
你可能意识到了这一点,但这个函数不是递归的,我想,它也不是你想要它做的

但是,在概念化函数在Ocaml中的工作方式时存在错误。您编写函数的方式本质上是必需的;它是一系列按顺序执行的
if/then
语句。相反,
euclid
的返回值应该只是一个广义的
if/then
语句的结果(一个整数值)。正如我在上面所做的那样,嵌套是可以接受的,但最重要的是,函数只是一个单独的表达式,需要计算,而不是一系列命令操作

编辑更新后的问题:

所有OCaml
if/then
语句都应该有
else
子句。最后一个嵌套的
if/then
语句没有
else
子句。如果OCaml检测到一个不带
else
子句的
If/then
语句,则假定一个
else
子句返回
()
(单位)。本质上,如果
a>b
为false,OCaml应该返回什么?它不假定任何内容,但返回的
()
与假定的函数类型(整数)冲突

当然,在函数中,
a>b
为false是不可能的,因为如果不是
a=b
而不是
a
,那么唯一的选择就是
a>b
。因此,在函数末尾不需要另一个
if
语句;此时,您毫无疑问地知道
a>b
,因此您可以简单地说
else 2