2012-07-05 73 views
4

我学习OCaml的,这是我的第一个类型的语言,所以请尽量宽容我:“鸿沟”Ocaml程序编写错误类型

对于实践中,我试图定义一个函数它输入两个int并输出一个布尔值,描述'int a'是否均匀分配到'int b'中。在我第一次尝试,我写了这样的事情:

let divides? a b = 
if a mod b = 0 then true 
else false;; 

这给了错误类型:

if a mod b = 0 then true 
^
Error: This expression has type 'a option 
     but an expression was expected of type int 

于是我试图扭转它,我这样做:

let divides? a b = 
match a mod b with 
    0 -> true 
|x -> false;; 

哪些没有多大帮助: Characters 26-27 match a mod b with ^ Error: This expression has type 'a option but an expression was expected of type int

然后我试过这个:

let divides? (a : int) (b : int) = 
match a mod b with 
0 -> true 
|x -> false;; 

其中,引起这样的: 字符14-15: 让分歧? (a:int)(b:int)= ^ 错误:此模式与int 类型的值匹配,但预期匹配'a选项类型值的模式。

对于现在的类型系统,我感到非常困惑和沮丧。 (我的第一语言是Scheme,这是我的第二语言。)任何帮助解释我要去哪里错误和建议如何解决它非常感谢。

+1

(正如在大多数语言中,你可以用''代替'if then true else false'。请注意。) – 2012-07-05 23:06:39

回答

12

问题是您不能使用问号字符在OCaml中的变量/函数名称中。它实际上解析你的函数声明是这样的:

let divides ?a b = 
    if a mod b = 0 then true 
    else false 

注意问号实际影响的a类型,而不是函数的名称的一部分。

这意味着aoptional parameter,所以对于某些'a它被分配了'a option的类型。

尝试从名称中删除问号。

+0

非常感谢!我疯了,检查教科书,浏览互联网上的每个站点以寻求答案......谢谢。 – Balthasar 2012-07-05 23:09:49

+0

没问题,很高兴我们可以帮忙! – Ashe 2012-07-05 23:41:09