2016-11-26 81 views
0

我已經寫了這個函數來計算兩個整數的總和,然後輸出它是一個int選項類型。但我得到這個警告。我已經定義了None情況,但我仍然得到這個。誰能幫忙?Ocaml選項功能

Error

let add x (Some y) = match x with 

|None -> if Some y = None then None 
     else Some y 
|Some x -> 
    let z = x + y in 
    if z > max_int then None 
    else if z < min_int then None 
    else if (Some y) = None then Some x 
    else Some (x + y) 

我這樣做,但仍缺少的東西。任何人都可以想到這不起作用的情況嗎?

let add x y = match (x, y) with 
| (None, None) -> None 
| (Some x, None) -> None 
| (None, Some y) -> None 
| (Some x, Some y) -> if x > max_int then None 
        else if x < 0 then None 
        else if y < 0 then None 
        else if x + y > max x y then None 
        else if x + y < min x y then None 
        else if y > max_int then None 
        else if x < min_int then None 
        else if y < min_int then None 
        else if x + y >= max_int then None 
        else if x + y <= min_int then None 
        else Some (x + y) 
+0

看來你試圖檢查溢出;但是你這樣做的方式是行不通的。例如,'x> max_int'永遠不會是真的,因爲'max_int'是'x'可以擁有的最大值。你可能想要檢查(例如)'x> max_int - y'的情況,其中'x'和'y'都是正數;這是真的,如果'x + y> max_int'(減去'y'兩邊),但是避免溢出。 –

+0

可以這樣測試 x + y> max_int - 1? – 1XCoderX1

+0

不可以。除了錯誤之外,問題是'max_int'是OCaml中整數可以具有的最大值;如果增加溢出,則它將環繞,例如, 'max_int + 1 = min_int'。這是你必須專門解決的問題(我建議的方法不是唯一的方法,但如果你希望證明它是正確的,可能是最簡單的方法)。 –

回答

2

問題是在這裏:let add x (Some y) = ...。 只有在第二個參數不是None的情況下,這定義了add

+0

請檢查編輯後的功能 – 1XCoderX1