Commit 5c17afb5 authored by Dan Grossman's avatar Dan Grossman
Browse files

add comments, mostly to indicate the NonNegInt example assumes there is no...

add comments, mostly to indicate the NonNegInt example assumes there is no integer overflow (for sake of a cute/elegant/simple example)
parent cdca4c76
......@@ -52,6 +52,13 @@ module type NONEGINT = sig
val to_int : t -> int (* why not t -> t ? *)
end
(* this example, thanks to the abstract type in NONEGINT, makes it impossible for a client
to make a value of type NonNegInt.t that is negative.
However, this is assuming (wrongly) that ints do not overflow. That assumption is useful
for a simple example that conveys the idea of relying on an abstraction, but in practice
due to overflow, we would need add and mul to check for negatives and return an option,
like sub, which makes the example less compelling. *)
module NonNegInt : NONEGINT = struct
type t = int
......@@ -62,10 +69,10 @@ module NonNegInt : NONEGINT = struct
Some i
let add a b =
a + b
a + b (* why not mknni (a * b) ? See comment above. *)
let mul a b =
a * b (* why not mknni (a * b) ? *)
a * b (* why not mknni (a * b) ? See comment above. *)
let sub a b =
mknni (a - b) (* why not a - b ? *)
......@@ -73,8 +80,10 @@ module NonNegInt : NONEGINT = struct
let to_int a = a (* external world doesn't know this "is it" *)
end
(* we may not have time for this longer example below, but it's
a nice example we might give an overview of
(* This example shows three different ways to implement the same abstraction where,
thanks to the abstract type, all three behave exactly the same for all clients.
Each uses a different data structure and therefore has different algorithms and
invariants.
*)
module type NONEMPTYLIST = sig
......@@ -136,7 +145,7 @@ module Nel_C : NONEMPTYLIST = struct
let cons x xs = x::xs
let tl xs =
match xs with
| [] -> failwith "impossible -- should never happen"
| [] -> failwith "impossible -- can never happen"
| x::[] -> failwith "tl of one-element list"
| x::xs' -> xs'
let hd = List.hd
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment