2016-11-26 85 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