Dividing by zero
----------------
-Integer division operation presupposes that its second argument
+Integer division presupposes that its second argument
(the divisor) is not zero, upon pain of presupposition failure.
Here's what my OCaml interpreter says:
So we want to explicitly allow for the possibility that
division will return something other than a number.
-We'll use OCaml's option type, which works like this:
+We'll use OCaml's `option` type, which works like this:
# type 'a option = None | Some of 'a;;
# None;;
- : int option = Some 3
So if a division is normal, we return some number, but if the divisor is
-zero, we return None. As a mnemonic aid, we'll append a `'` to the end of our new divide function.
+zero, we return `None`. As a mnemonic aid, we'll append a `'` to the end of our new divide function.
<pre>
let div' (x:int) (y:int) =
- match y with 0 -> None |
- _ -> Some (x / y);;
+ match y with
+ 0 -> None
+ | _ -> Some (x / y);;
(*
val div' : int -> int -> int option = fun
<pre>
let div' (x:int option) (y:int option) =
- match y with None -> None |
- Some 0 -> None |
- Some n -> (match x with None -> None |
- Some m -> Some (m / n));;
+ match y with
+ None -> None
+ | Some 0 -> None
+ | Some n -> (match x with
+ None -> None
+ | Some m -> Some (m / n));;
(*
val div' : int option -> int option -> int option = <fun>
<pre>
let div' (x:int option) (y:int option) =
- match (x, y) with (None, _) -> None |
- (_, None) -> None |
- (_, Some 0) -> None |
- (Some m, Some n) -> Some (m / n);;
+ match (x, y) with
+ (None, _) -> None
+ | (_, None) -> None
+ | (_, Some 0) -> None
+ | (Some m, Some n) -> Some (m / n);;
</pre>
So far so good. But what if we want to combine division with
<pre>
let add' (x:int option) (y:int option) =
- match (x, y) with (None, _) -> None |
- (_, None) -> None |
- (Some m, Some n) -> Some (m + n);;
+ match (x, y) with
+ (None, _) -> None
+ | (_, None) -> None
+ | (Some m, Some n) -> Some (m + n);;
(*
val add' : int option -> int option -> int option = <fun>
<pre>
let bind' (x: int option) (f: int -> (int option)) =
- match x with None -> None |
- Some n -> f n;;
+ match x with
+ None -> None
+ | Some n -> f n;;
let add' (x: int option) (y: int option) =
bind' x (fun x -> bind' y (fun y -> Some (x + y)));;