swap example extended

parent 970ead57
(* Swapping two integers in-place *)
module Swap
use import int.Int
......@@ -13,3 +15,60 @@ module Swap
a := !a - !b
end
(* It also works fine with machine integers, even with overflows *)
module SwapInt32
use import int.Int
use import ref.Ref
(* a simple model of 32-bit integers with addition, subtraction,
and possible overflows *)
type int32
constant min_int32 : int = - 0x80000000
constant max_int32 : int = 0x7fffffff
constant width : int = max_int32 - min_int32 + 1
function to_int (n: int32) : int
val (+) (a: int32) (b: int32) : int32
ensures { to_int result =
if to_int a + to_int b < min_int32 then to_int a + to_int b + width
else if to_int a + to_int b > max_int32 then to_int a + to_int b - width
else to_int a + to_int b }
val (-) (a: int32) (b: int32) : int32
ensures { to_int result =
if to_int a - to_int b < min_int32 then to_int a - to_int b + width
else if to_int a - to_int b > max_int32 then to_int a - to_int b - width
else to_int a - to_int b }
predicate in_bounds (n: int32) = min_int32 <= to_int n <= max_int32
(* purely applicative version first *)
let swap (a b: int32) : (int32, int32)
requires { in_bounds a /\ in_bounds b }
ensures { let (x,y) = result in
to_int x = to_int b /\ to_int y = to_int a }
=
let a = a + b in
let b = a - b in
let a = a - b in
(a, b)
(* then rephrased with mutable variables *)
let swap_ref (a b: ref int32) : unit
requires { in_bounds !a /\ in_bounds !b }
writes { a, b }
ensures { to_int !a = old (to_int !b) /\ to_int !b = old (to_int !a) }
=
a := !a + !b;
b := !a - !b;
a := !a - !b
end
......@@ -2,12 +2,21 @@
<!DOCTYPE why3session PUBLIC "-//Why3//proof session v5//EN"
"http://why3.lri.fr/why3session.dtd">
<why3session shape_version="4">
<prover id="0" name="Alt-Ergo" version="0.99.1" timelimit="6" memlimit="1000"/>
<prover id="0" name="Alt-Ergo" version="0.99.1" timelimit="6" steplimit="1" memlimit="1000"/>
<prover id="1" name="Alt-Ergo" version="1.01" timelimit="6" steplimit="0" memlimit="1000"/>
<file name="../swap.mlw" expanded="true">
<theory name="Swap" sum="03a7896fac9253beb9bec761b34a8f38" expanded="true">
<goal name="WP_parameter swap" expl="VC for swap" expanded="true">
<proof prover="0"><result status="valid" time="0.01" steps="3"/></proof>
</goal>
</theory>
<theory name="SwapInt32" sum="9bb36b825ac35507474d005be97b8091" expanded="true">
<goal name="WP_parameter swap" expl="VC for swap" expanded="true">
<proof prover="1"><result status="valid" time="0.01" steps="49"/></proof>
</goal>
<goal name="WP_parameter swap_ref" expl="VC for swap_ref" expanded="true">
<proof prover="1"><result status="valid" time="0.02" steps="49"/></proof>
</goal>
</theory>
</file>
</why3session>
Markdown is supported
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