2012-07-05 37 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