test_ID
stringlengths
3
3
test_file
stringlengths
14
119
ground_truth
stringlengths
70
28.7k
hints_removed
stringlengths
58
28.7k
200
Dafny_tmp_tmpmvs2dmry_examples2.dfy
method add_by_inc(x: nat, y:nat) returns (z:nat) ensures z == x+y; { z := x; var i := 0; while (i < y) decreases y-i; invariant 0 <= i <= y; invariant z == x + i; { z := z+1; i := i+1; } assert (z == x+y); assert (i == y); } method Product(m: nat, n:nat) returns (res:nat) ensures res == m*n; { var m1: nat := m; res:=0; while (m1 != 0) invariant 0 <= m1 <= m; decreases m1; invariant res == (m-m1)*n; { var n1: nat := n; while (n1 != 0) invariant 0 <= n1 <= n; decreases n1; invariant res == (m-m1)*n + (n-n1); { res := res+1; n1 := n1-1; } m1 := m1-1; } } method gcdCalc(m: nat, n: nat) returns (res: nat) requires m>0 && n>0; ensures res == gcd(m,n); { var m1 : nat := m; var n1 : nat := n; while (m1 != n1) invariant 0< m1 <=m; invariant 0 < n1 <=n; invariant gcd(m,n) == gcd (m1,n1) decreases m1+n1; { if( m1>n1) { m1 := m1- n1; } else { n1:= n1-m1; } } return n1; } function gcd(m: nat, n: nat) : nat requires m>0 && n>0; decreases m+n { if(m==n) then n else if( m > n) then gcd(m-n,n) else gcd(m, n-m) } method exp_by_sqr(x0: real, n0: nat) returns (r:real) requires x0 >= 0.0; ensures r == exp(x0, n0); { if(n0 == 0) {return 1.0;} if(x0 == 0.0) {return 0.0;} var x,n,y := x0, n0, 1.0; while(n>1) invariant 1<=n<=n0; invariant exp(x0,n0) == exp(x,n) * y; decreases n; { if( n % 2 == 0) { assume (exp(x,n) == exp(x*x,n/2)); x := x*x; n:= n/2; } else { assume (exp(x,n) == exp(x*x,(n-1)/2) * x); y:=x*y; x:=x*x; n:=(n-1)/2; } } // assert (exp(x0,n0) == exp(x,n) * y); // assert (x*y == exp(x0,n0)); return x*y; } function exp(x: real, n: nat) :real decreases n; { if(n == 0) then 1.0 else if (x==0.0) then 0.0 else if (n ==0 && x == 0.0) then 1.0 else x*exp(x, n-1) } // method add_by_inc_vc(x: int, y:int) returns (z:int) // { // assume x>=0 && y>=0; // z := x; // var i := 0; // assert 0 <= i <= y && z == x + i; // z,i = *,*; // assume 0 <= i <= y && z == x + i; // if (i < y) // { // ghost var rank0 := y-i // z := z+1; // i := i+1; // assert(y-i < rank0) // ghost var rank1 := y-i // assert(rank1 < rank0) // assert(rank1 >=0) // assert 0 <= i <= y && z == x + i; // assume(false); // } // assert (z == x+y); // assert (i == y); // return z; // }
method add_by_inc(x: nat, y:nat) returns (z:nat) ensures z == x+y; { z := x; var i := 0; while (i < y) { z := z+1; i := i+1; } } method Product(m: nat, n:nat) returns (res:nat) ensures res == m*n; { var m1: nat := m; res:=0; while (m1 != 0) { var n1: nat := n; while (n1 != 0) { res := res+1; n1 := n1-1; } m1 := m1-1; } } method gcdCalc(m: nat, n: nat) returns (res: nat) requires m>0 && n>0; ensures res == gcd(m,n); { var m1 : nat := m; var n1 : nat := n; while (m1 != n1) { if( m1>n1) { m1 := m1- n1; } else { n1:= n1-m1; } } return n1; } function gcd(m: nat, n: nat) : nat requires m>0 && n>0; { if(m==n) then n else if( m > n) then gcd(m-n,n) else gcd(m, n-m) } method exp_by_sqr(x0: real, n0: nat) returns (r:real) requires x0 >= 0.0; ensures r == exp(x0, n0); { if(n0 == 0) {return 1.0;} if(x0 == 0.0) {return 0.0;} var x,n,y := x0, n0, 1.0; while(n>1) { if( n % 2 == 0) { assume (exp(x,n) == exp(x*x,n/2)); x := x*x; n:= n/2; } else { assume (exp(x,n) == exp(x*x,(n-1)/2) * x); y:=x*y; x:=x*x; n:=(n-1)/2; } } // assert (exp(x0,n0) == exp(x,n) * y); // assert (x*y == exp(x0,n0)); return x*y; } function exp(x: real, n: nat) :real { if(n == 0) then 1.0 else if (x==0.0) then 0.0 else if (n ==0 && x == 0.0) then 1.0 else x*exp(x, n-1) } // method add_by_inc_vc(x: int, y:int) returns (z:int) // { // assume x>=0 && y>=0; // z := x; // var i := 0; // assert 0 <= i <= y && z == x + i; // z,i = *,*; // assume 0 <= i <= y && z == x + i; // if (i < y) // { // ghost var rank0 := y-i // z := z+1; // i := i+1; // assert(y-i < rank0) // ghost var rank1 := y-i // assert(rank1 < rank0) // assert(rank1 >=0) // assert 0 <= i <= y && z == x + i; // assume(false); // } // assert (z == x+y); // assert (i == y); // return z; // }
201
Dafny_tmp_tmpmvs2dmry_pancakesort_findmax.dfy
// returns an index of the largest element of array 'a' in the range [0..n) method findMax (a : array<int>, n : int) returns (r:int) requires a.Length > 0 requires 0 < n <= a.Length ensures 0 <= r < n <= a.Length; ensures forall k :: 0 <= k < n <= a.Length ==> a[r] >= a[k]; ensures multiset(a[..]) == multiset(old(a[..])); { var mi; var i; mi := 0; i := 0; while (i < n) invariant 0 <= i <= n <= a.Length; invariant 0 <= mi < n; invariant forall k :: 0 <= k < i ==> a[mi] >= a[k]; decreases n-i; { if (a[i] > a[mi]) { mi := i; } i := i + 1; } return mi; }
// returns an index of the largest element of array 'a' in the range [0..n) method findMax (a : array<int>, n : int) returns (r:int) requires a.Length > 0 requires 0 < n <= a.Length ensures 0 <= r < n <= a.Length; ensures forall k :: 0 <= k < n <= a.Length ==> a[r] >= a[k]; ensures multiset(a[..]) == multiset(old(a[..])); { var mi; var i; mi := 0; i := 0; while (i < n) { if (a[i] > a[mi]) { mi := i; } i := i + 1; } return mi; }
202
Dafny_tmp_tmpmvs2dmry_pancakesort_flip.dfy
// flips (i.e., reverses) array elements in the range [0..num] method flip (a: array<int>, num: int) requires a.Length > 0; requires 0 <= num < a.Length; modifies a; ensures forall k :: 0 <= k <= num ==> a[k] == old(a[num-k]) ensures forall k :: num < k < a.Length ==> a[k] == old(a[k]) // ensures multiset(a[..]) == old(multiset(a[..])) { var tmp:int; var i := 0; var j := num; while (i < j) decreases j // invariant 0 <= i < j <= num invariant i + j == num invariant 0 <= i <= num/2+1 invariant num/2 <= j <= num invariant forall n :: 0 <= n < i ==> a[n] == old(a[num-n]) invariant forall n :: 0 <= n < i ==> a[num-n]==old(a[n]) invariant forall k :: i <= k <= j ==> a[k] == old(a[k]) invariant forall k :: num < k < a.Length ==> a[k] == old(a[k]) { tmp := a[i]; a[i] := a[j]; a[j] := tmp; i := i + 1; j := j - 1; } }
// flips (i.e., reverses) array elements in the range [0..num] method flip (a: array<int>, num: int) requires a.Length > 0; requires 0 <= num < a.Length; modifies a; ensures forall k :: 0 <= k <= num ==> a[k] == old(a[num-k]) ensures forall k :: num < k < a.Length ==> a[k] == old(a[k]) // ensures multiset(a[..]) == old(multiset(a[..])) { var tmp:int; var i := 0; var j := num; while (i < j) // invariant 0 <= i < j <= num { tmp := a[i]; a[i] := a[j]; a[j] := tmp; i := i + 1; j := j - 1; } }
203
Dafny_tmp_tmpv_d3qi10_2_min.dfy
function min(a: int, b: int): int ensures min(a, b) <= a && min(a, b) <= b ensures min(a, b) == a || min(a, b) == b { if a < b then a else b } method minMethod(a: int, b: int) returns (c: int) ensures c <= a && c <= b ensures c == a || c == b // Ou encore: ensures c == min(a, b) { if a < b { c := a; } else { c := b; } } ghost function minFunction(a: int, b: int): int ensures minFunction(a, b) <= a && minFunction(a, b) <= b ensures minFunction(a, b) == a || minFunction(a, b) == b { if a < b then a else b } // Return a minimum of a. method minArray(a: array<int>) returns (m: int) requires a!= null && a.Length > 0 ; ensures forall k | 0 <= k < a.Length :: m <= a[k] ensures exists k | 0 <= k < a.Length :: m == a[k] { /* TODO */ m := a[0]; // Initialise m avec le premier élément du tableau var i := 1; while i < a.Length invariant 0 <= i <= a.Length invariant forall k | 0 <= k < i :: m <= a[k] invariant exists k | 0 <= k < i :: m == a[k] { /* TODO */ if a[i] < m { m := a[i]; } i := i + 1; } } method Main(){ var integer:= min(1,2); print(integer); }
function min(a: int, b: int): int ensures min(a, b) <= a && min(a, b) <= b ensures min(a, b) == a || min(a, b) == b { if a < b then a else b } method minMethod(a: int, b: int) returns (c: int) ensures c <= a && c <= b ensures c == a || c == b // Ou encore: ensures c == min(a, b) { if a < b { c := a; } else { c := b; } } ghost function minFunction(a: int, b: int): int ensures minFunction(a, b) <= a && minFunction(a, b) <= b ensures minFunction(a, b) == a || minFunction(a, b) == b { if a < b then a else b } // Return a minimum of a. method minArray(a: array<int>) returns (m: int) requires a!= null && a.Length > 0 ; ensures forall k | 0 <= k < a.Length :: m <= a[k] ensures exists k | 0 <= k < a.Length :: m == a[k] { /* TODO */ m := a[0]; // Initialise m avec le premier élément du tableau var i := 1; while i < a.Length { /* TODO */ if a[i] < m { m := a[i]; } i := i + 1; } } method Main(){ var integer:= min(1,2); print(integer); }
204
Dafny_tmp_tmpv_d3qi10_3_cumsum.dfy
function sum(a: array<int>, i: int): int requires 0 <= i < a.Length reads a { a[i] + if i == 0 then 0 else sum(a, i - 1) } method cumsum(a: array<int>, b: array<int>) requires a.Length == b.Length && a.Length > 0 && a != b // when you change a , that's not the same object than b . //requires b.Length > 0 ensures forall i | 0 <= i < a.Length :: b[i] == sum(a, i) modifies b { b[0] := a[0]; // Initialise le premier élément de b var i := 1; while i < a.Length invariant 1 <= i <= a.Length invariant forall i' | 0 <= i' < i :: b[i'] == sum(a, i') { b[i] := b[i - 1] + a[i]; // Calcule la somme cumulée pour chaque élément i := i + 1; } }
function sum(a: array<int>, i: int): int requires 0 <= i < a.Length reads a { a[i] + if i == 0 then 0 else sum(a, i - 1) } method cumsum(a: array<int>, b: array<int>) requires a.Length == b.Length && a.Length > 0 && a != b // when you change a , that's not the same object than b . //requires b.Length > 0 ensures forall i | 0 <= i < a.Length :: b[i] == sum(a, i) modifies b { b[0] := a[0]; // Initialise le premier élément de b var i := 1; while i < a.Length { b[i] := b[i - 1] + a[i]; // Calcule la somme cumulée pour chaque élément i := i + 1; } }
205
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab10_Lab10.dfy
predicate IsOdd(x: int) { x % 2 == 1 } newtype Odd = n : int | IsOdd(n) witness 3 trait OddListSpec { var s: seq<Odd> var capacity: nat predicate Valid() reads this { 0 <= |s| <= this.capacity && forall i :: 0 <= i < |s| ==> IsOdd(s[i] as int) } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |s| method at(index: nat) returns (x: Odd) requires 0 <= index < |s| method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| } class OddList extends OddListSpec { constructor (capacity: nat) ensures Valid() ensures |s| == 0 ensures this.capacity == capacity { s := []; this.capacity := capacity; } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() { var tail := s[index..]; s := s[..index] + [element]; s := s + tail; } method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() { insert(0, element); } method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() { insert(|s|, element); } method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: int := 0 to |s| invariant 0 <= i <= |s| invariant forall k :: 0 <= k < i ==> s[k] != element { if s[i] == element { s := s[..i] + s[i + 1..]; break; } } } method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { s := s[..index] + s[index + 1..]; } method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[0]; s := s[1..]; } method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[|s| - 1]; s := s[..|s| - 1]; } method length() returns (n: nat) ensures n == |s| { return |s|; } method at(index: nat) returns (x: Odd) requires 0 <= index < |s| ensures s[index] == x { return s[index]; } method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] { var left, right := 0, |s|; while left < right invariant 0 <= left <= right <= |s| invariant element !in s[..left] && element !in s[right..] { var mid := (left + right) / 2; if element < s[mid] { right := mid; } else if s[mid] < element { left := mid + 1; } else { return mid; } } return -1; } method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| { l := new OddList(this.capacity + l2.capacity); var i, j := 0, 0; while i < |s| || j < |l2.s| invariant 0 <= i <= |s| invariant 0 <= j <= |l2.s| invariant i + j == |l.s| invariant |l.s| <= l.capacity invariant l.capacity == this.capacity + l2.capacity decreases |s| - i, |l2.s| - j { if i == |s| { if j == |l2.s| { return l; } else { l.pushBack(l2.s[j]); j := j + 1; } } else { if j == |l2.s| { l.pushBack(s[i]); i := i + 1; } else { if s[i] < l2.s[j] { l.pushBack(s[i]); i := i + 1; } else { l.pushBack(l2.s[j]); j := j + 1; } } } } return l; } } trait CircularLinkedListSpec<T(==)> { var l: seq<T> var capacity: nat predicate Valid() reads this { 0 <= |l| <= this.capacity } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |l| method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] } class CircularLinkedList<T(==)> extends CircularLinkedListSpec<T> { constructor (capacity: nat) requires capacity >= 0 ensures Valid() ensures |l| == 0 ensures this.capacity == capacity { l := []; this.capacity := capacity; } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() { if (|l| == 0) { l := [element]; } else { var actualIndex := index % |l|; var tail := l[actualIndex..]; l := l[..actualIndex] + [element]; l := l + tail; } } method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: nat := 0 to |l| invariant 0 <= i <= |l| invariant forall k :: 0 <= k < i ==> l[k] != element { if l[i] == element { l := l[..i] + l[i + 1..]; break; } } } method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { var actualIndex := index % |l|; l := l[..actualIndex] + l[actualIndex + 1..]; } method length() returns (n: nat) ensures n == |l| { return |l|; } method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x { var actualIndex := index % |l|; return l[actualIndex]; } method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] { if (|l| == 1) { x := l[0]; } else { var actualIndex := index % |l|; if (actualIndex == (|l| - 1)) { x := l[0]; } else { x := l[actualIndex + 1]; } } return x; } method isIn(element: T) returns (b: bool) ensures |l| == 0 ==> b == false ensures |l| > 0 && b == true ==> exists i :: 0 <= i < |l| && l[i] == element ensures |l| > 0 && b == false ==> !exists i :: 0 <= i < |l| && l[i] == element { if (|l| == 0) { b := false; } else { b := false; for i: nat := 0 to |l| invariant 0 <= i <= |l| invariant forall k :: 0 <= k < i ==> l[k] != element { if l[i] == element { b := true; break; } } } } }
predicate IsOdd(x: int) { x % 2 == 1 } newtype Odd = n : int | IsOdd(n) witness 3 trait OddListSpec { var s: seq<Odd> var capacity: nat predicate Valid() reads this { 0 <= |s| <= this.capacity && forall i :: 0 <= i < |s| ==> IsOdd(s[i] as int) } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |s| method at(index: nat) returns (x: Odd) requires 0 <= index < |s| method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| } class OddList extends OddListSpec { constructor (capacity: nat) ensures Valid() ensures |s| == 0 ensures this.capacity == capacity { s := []; this.capacity := capacity; } method insert(index: nat, element: Odd) modifies this requires 0 <= index <= |s| requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[index] == element ensures old(capacity) == capacity ensures Valid() { var tail := s[index..]; s := s[..index] + [element]; s := s + tail; } method pushFront(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[0] == element ensures old(capacity) == capacity ensures Valid() { insert(0, element); } method pushBack(element: Odd) modifies this requires |s| + 1 <= this.capacity ensures |s| == |old(s)| + 1 ensures s[|s| - 1] == element ensures old(capacity) == capacity ensures Valid() { insert(|s|, element); } method remove(element: Odd) modifies this requires Valid() requires |s| > 0 requires element in s ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: int := 0 to |s| { if s[i] == element { s := s[..i] + s[i + 1..]; break; } } } method removeAtIndex(index: nat) modifies this requires Valid() requires |s| > 0 requires 0 <= index < |s| ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { s := s[..index] + s[index + 1..]; } method popFront() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[0] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[0]; s := s[1..]; } method popBack() returns (x: Odd) modifies this requires Valid() requires |s| > 0 ensures old(s)[|old(s)| - 1] == x ensures |s| == |old(s)| - 1 ensures old(capacity) == capacity ensures Valid() { x := s[|s| - 1]; s := s[..|s| - 1]; } method length() returns (n: nat) ensures n == |s| { return |s|; } method at(index: nat) returns (x: Odd) requires 0 <= index < |s| ensures s[index] == x { return s[index]; } method BinarySearch(element: Odd) returns (index: int) requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] ensures 0 <= index ==> index < |s| && s[index] == element ensures index == -1 ==> element !in s[..] { var left, right := 0, |s|; while left < right { var mid := (left + right) / 2; if element < s[mid] { right := mid; } else if s[mid] < element { left := mid + 1; } else { return mid; } } return -1; } method mergedWith(l2: OddList) returns (l: OddList) requires Valid() requires l2.Valid() requires this.capacity >= 0 requires l2.capacity >= 0 requires forall i, j :: 0 <= i < j < |s| ==> s[i] <= s[j] requires forall i, j :: 0 <= i < j < |l2.s| ==> l2.s[i] <= l2.s[j] ensures l.capacity == this.capacity + l2.capacity ensures |l.s| == |s| + |l2.s| { l := new OddList(this.capacity + l2.capacity); var i, j := 0, 0; while i < |s| || j < |l2.s| { if i == |s| { if j == |l2.s| { return l; } else { l.pushBack(l2.s[j]); j := j + 1; } } else { if j == |l2.s| { l.pushBack(s[i]); i := i + 1; } else { if s[i] < l2.s[j] { l.pushBack(s[i]); i := i + 1; } else { l.pushBack(l2.s[j]); j := j + 1; } } } } return l; } } trait CircularLinkedListSpec<T(==)> { var l: seq<T> var capacity: nat predicate Valid() reads this { 0 <= |l| <= this.capacity } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() method length() returns (n: nat) ensures n == |l| method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] } class CircularLinkedList<T(==)> extends CircularLinkedListSpec<T> { constructor (capacity: nat) requires capacity >= 0 ensures Valid() ensures |l| == 0 ensures this.capacity == capacity { l := []; this.capacity := capacity; } method insert(index: int, element: T) // allows for integer and out-of-bounds index due to circularity // managed by applying modulus modifies this requires |l| + 1 <= this.capacity ensures |old(l)| == 0 ==> l == [element] ensures |l| == |old(l)| + 1 ensures |old(l)| > 0 ==> l[index % |old(l)|] == element ensures old(capacity) == capacity ensures Valid() { if (|l| == 0) { l := [element]; } else { var actualIndex := index % |l|; var tail := l[actualIndex..]; l := l[..actualIndex] + [element]; l := l + tail; } } method remove(element: T) modifies this requires Valid() requires |l| > 0 requires element in l ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { for i: nat := 0 to |l| { if l[i] == element { l := l[..i] + l[i + 1..]; break; } } } method removeAtIndex(index: int) modifies this requires Valid() requires |l| > 0 ensures |l| == |old(l)| - 1 ensures old(capacity) == capacity ensures Valid() { var actualIndex := index % |l|; l := l[..actualIndex] + l[actualIndex + 1..]; } method length() returns (n: nat) ensures n == |l| { return |l|; } method at(index: int) returns (x: T) requires |l| > 0 ensures l[index % |l|] == x { var actualIndex := index % |l|; return l[actualIndex]; } method nextAfter(index: int) returns (x: T) requires |l| > 0 ensures |l| == 1 ==> x == l[0] ensures |l| > 1 && index % |l| == (|l| - 1) ==> x == l[0] ensures |l| > 1 && 0 <= index && |l| < (|l| - 1) ==> x == l[index % |l| + 1] { if (|l| == 1) { x := l[0]; } else { var actualIndex := index % |l|; if (actualIndex == (|l| - 1)) { x := l[0]; } else { x := l[actualIndex + 1]; } } return x; } method isIn(element: T) returns (b: bool) ensures |l| == 0 ==> b == false ensures |l| > 0 && b == true ==> exists i :: 0 <= i < |l| && l[i] == element ensures |l| > 0 && b == false ==> !exists i :: 0 <= i < |l| && l[i] == element { if (|l| == 0) { b := false; } else { b := false; for i: nat := 0 to |l| { if l[i] == element { b := true; break; } } } } }
206
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab1_Lab1.dfy
/// Types defined as part of Tasks 3, 5 and 9 // Since we have created the IsOddNat predicate we use it to define the new Odd subsort newtype Odd = n : int | IsOddNat(n) witness 1 // Since we have created the IsEvenNat predicate we use it to define the new Even subsort newtype Even = n : int | IsEvenNat(n) witness 2 /* * We use int as the native type, so that the basic operations are available. * However, we restrict the domain in order to accomodate the requirements. */ newtype int32 = n: int | -2147483648 <= n < 2147483648 witness 3 /// Task 2 /* * In order for an integer to be a natural, odd number, two requirements must be satisfied: * The integer in cause must be positive and the remainder of the division by 2 must be 1. */ predicate IsOddNat(x: int) { (x >= 0) && (x % 2 == 1) } /// Task 4 /* * In order for an integer to be a natural, even number, two requirements must be satisfied: * The integer in cause must be positive and the remainder of the division by 2 must be 0. */ predicate IsEvenNat(x: int) { (x >= 0) && (x % 2 == 0) } /// Task 6 /* * In order to prove the statement, we rewrite the two numbers to reflect their form: * The sum between a multiple of 2 and 1. * * By rewriting them like this and then adding them together, the sum is shown to * be a multiple of 2 and thus, an even number. */ lemma AdditionOfTwoOddsResultsInEven(x: int, y: int) requires IsOddNat(x); requires IsOddNat(y); ensures IsEvenNat(x + y); { calc { IsOddNat(x); x % 2 == 1; } calc { IsOddNat(y); y % 2 == 1; } calc { (x + y) % 2 == 0; IsEvenNat(x + y); true; } } /// Task 7 /* * In order for an integer to be a natural, prime number, two requirements must be satisfied: * The integer in cause must be natural (positive) and must have exactly two divisors: * 1 and itself. * * Aside from two, which is the only even prime, we test the primality by checking if there * is no number greater or equal to 2 that the number in cause is divisible with. */ predicate IsPrime(x: int) requires x >= 0; { x == 2 || forall d :: 2 <= d < x ==> x % d != 0 } /// Task 8 /* * It is a known fact that any prime divided by any number, aside from 1 and itself, * will yield a non-zero remainder. * * Thus, when dividing a prime (other than 2) by 2, the only non-zero remainder possible * is 1, therefore making the number an odd one. */ lemma AnyPrimeGreaterThanTwoIsOdd(x : int) requires x > 2; requires IsPrime(x); ensures IsOddNat(x); { calc { x % 2; { assert forall d :: 2 <= d < x ==> x % d != 0; } 1; } calc { IsOddNat(x); (x >= 0) && (x % 2 == 1); { assert x > 2; } true && true; true; } } /* * Task 9 * Defined the basic arithmetic functions. * Also defined the absolute value. * * Over/Underflow are represented by the return of 0. */ function add(x: int32, y: int32): int32 { if (-2147483648 <= (x as int) + (y as int) <= 2147483647) then x + y else 0 } function sub(x: int32, y: int32): int32 { if (-2147483648 <= (x as int) - (y as int) <= 2147483647) then x - y else 0 } function mul(x: int32, y: int32): int32 { if (-2147483648 <= (x as int) * (y as int) <= 2147483647) then x * y else 0 } function div(x: int32, y: int32): int32 requires y != 0; { if (-2147483648 <= (x as int) / (y as int) <= 2147483647) then x / y else 0 } function mod(x: int32, y: int32): int32 requires y != 0; { x % y /* * Given that y is int32 and * given that the remainder is positive and smaller than the denominator * the result cannot over/underflow and is, therefore, not checked */ } function abs(x: int32): (r: int32) ensures r >= 0; { if (x == -2147483648) then 0 else if (x < 0) then -x else x }
/// Types defined as part of Tasks 3, 5 and 9 // Since we have created the IsOddNat predicate we use it to define the new Odd subsort newtype Odd = n : int | IsOddNat(n) witness 1 // Since we have created the IsEvenNat predicate we use it to define the new Even subsort newtype Even = n : int | IsEvenNat(n) witness 2 /* * We use int as the native type, so that the basic operations are available. * However, we restrict the domain in order to accomodate the requirements. */ newtype int32 = n: int | -2147483648 <= n < 2147483648 witness 3 /// Task 2 /* * In order for an integer to be a natural, odd number, two requirements must be satisfied: * The integer in cause must be positive and the remainder of the division by 2 must be 1. */ predicate IsOddNat(x: int) { (x >= 0) && (x % 2 == 1) } /// Task 4 /* * In order for an integer to be a natural, even number, two requirements must be satisfied: * The integer in cause must be positive and the remainder of the division by 2 must be 0. */ predicate IsEvenNat(x: int) { (x >= 0) && (x % 2 == 0) } /// Task 6 /* * In order to prove the statement, we rewrite the two numbers to reflect their form: * The sum between a multiple of 2 and 1. * * By rewriting them like this and then adding them together, the sum is shown to * be a multiple of 2 and thus, an even number. */ lemma AdditionOfTwoOddsResultsInEven(x: int, y: int) requires IsOddNat(x); requires IsOddNat(y); ensures IsEvenNat(x + y); { calc { IsOddNat(x); x % 2 == 1; } calc { IsOddNat(y); y % 2 == 1; } calc { (x + y) % 2 == 0; IsEvenNat(x + y); true; } } /// Task 7 /* * In order for an integer to be a natural, prime number, two requirements must be satisfied: * The integer in cause must be natural (positive) and must have exactly two divisors: * 1 and itself. * * Aside from two, which is the only even prime, we test the primality by checking if there * is no number greater or equal to 2 that the number in cause is divisible with. */ predicate IsPrime(x: int) requires x >= 0; { x == 2 || forall d :: 2 <= d < x ==> x % d != 0 } /// Task 8 /* * It is a known fact that any prime divided by any number, aside from 1 and itself, * will yield a non-zero remainder. * * Thus, when dividing a prime (other than 2) by 2, the only non-zero remainder possible * is 1, therefore making the number an odd one. */ lemma AnyPrimeGreaterThanTwoIsOdd(x : int) requires x > 2; requires IsPrime(x); ensures IsOddNat(x); { calc { x % 2; { } 1; } calc { IsOddNat(x); (x >= 0) && (x % 2 == 1); { } true && true; true; } } /* * Task 9 * Defined the basic arithmetic functions. * Also defined the absolute value. * * Over/Underflow are represented by the return of 0. */ function add(x: int32, y: int32): int32 { if (-2147483648 <= (x as int) + (y as int) <= 2147483647) then x + y else 0 } function sub(x: int32, y: int32): int32 { if (-2147483648 <= (x as int) - (y as int) <= 2147483647) then x - y else 0 } function mul(x: int32, y: int32): int32 { if (-2147483648 <= (x as int) * (y as int) <= 2147483647) then x * y else 0 } function div(x: int32, y: int32): int32 requires y != 0; { if (-2147483648 <= (x as int) / (y as int) <= 2147483647) then x / y else 0 } function mod(x: int32, y: int32): int32 requires y != 0; { x % y /* * Given that y is int32 and * given that the remainder is positive and smaller than the denominator * the result cannot over/underflow and is, therefore, not checked */ } function abs(x: int32): (r: int32) ensures r >= 0; { if (x == -2147483648) then 0 else if (x < 0) then -x else x }
207
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab2_Lab2.dfy
/* * Task 2: Define the natural numbers as an algebraic data type * * Being an inductive data type, it's required that we have a base case constructor and an inductive one. */ datatype Nat = Zero | S(Pred: Nat) /// Task 2 // Exercise (a'): proving that the successor constructor is injective /* * It's known that the successors are equal. * It's know that for equal inputs, a non-random function returns the same result. * Thus, the predecessors of the successors, namely, the numbers themselves, are equal. */ lemma SIsInjective(x: Nat, y: Nat) ensures S(x) == S(y) ==> x == y { assume S(x) == S(y); assert S(x).Pred == S(y).Pred; assert x == y; } // Exercise (a''): Zero is different from successor(x), for any x /* * For all x: Nat, S(x) is built using the S constructor, implying that S(x).Zero? is inherently false. */ lemma ZeroIsDifferentFromSuccessor(n: Nat) ensures S(n) != Zero { assert S(n).Zero? == false; } // Exercise (b): inductively defining the addition of natural numbers /* * The function decreases y until it reaches the base inductive case. * The Addition between Zero and a x: Nat will be x. * The Addition between a successor of a y': Nat and another x: Nat is the successor of the Addition between y' and x * * x + y = 1 + ((x - 1) + y) */ function Add(x: Nat, y: Nat) : Nat decreases y { match y case Zero => x case S(y') => S(Add(x, y')) } // Exercise (c'): proving that the addition is commutative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Neutral. */ lemma {:induction n} ZeroAddNeutral(n: Nat) ensures Add(n, Zero) == Add(Zero, n) == n { match n case Zero => { assert Add(n, Zero) == Add(Zero, Zero) == Add(Zero, n) == n; } case S(n') => { assert Add(n, Zero) == Add(S(n'), Zero) == S(n') == Add(Zero, S(n')) == Add(Zero, n) == n; } } /* * Since Zero is neutral, it is trivial that the order of addition is not of importance. */ lemma {:induction n} ZeroAddCommutative(n: Nat) ensures Add(Zero, n) == Add(n, Zero) { assert Add(Zero, n) == n == Add(n, Zero); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddCommutative(x: Nat, y: Nat) ensures Add(x, y) == Add(y, x) decreases x, y { match x case Zero => ZeroAddCommutative(y); case S(x') => AddCommutative(x', y); } // Exercise (c''): proving that the addition is associative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Associative. * * Again, given that addition with Zero is neutral, the order of calculations is irrelevant. */ lemma {:induction x, y} ZeroAddAssociative(x: Nat, y: Nat) ensures Add(Add(Zero, x), y) == Add(Zero, Add(x, y)) { ZeroAddNeutral(x); assert Add(Add(Zero, x), y) == // ZeroAddNeutral Add(x, y) == Add(Zero, Add(x, y)); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddAssociative(x: Nat, y: Nat, z: Nat) ensures Add(Add(x, y), z) == Add(x, Add(y, z)) decreases z { match z case Zero => ZeroAddAssociative(Add(x, y), Zero); case S(z') => AddAssociative(x, y, z'); } // Exercise (d): defining a predicate lt(m, n) that holds when m is less than n /* * If x is Zero and y is a Successor, given that we have proven ZeroIsDifferentFromSuccessor for all x, the predicate holds. * Otherwise, if both are successors, we inductively check their predecessors. */ predicate LessThan(x: Nat, y: Nat) decreases x, y { (x.Zero? && y.S?) || (x.S? && y.S? && LessThan(x.Pred, y.Pred)) } // Exercise (e): proving that lt is transitive /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that LessThan is Transitive having a Zero as the left-most parameter. * * We prove this statement using Reductio Ad Absurdum. * We suppose that Zero is not smaller that an arbitrary z that is non-Zero. * This would imply that Zero has to be a Successor (i.e. Zero.S? == true). * This is inherently false. */ lemma {:induction y, z} LessThanIsTransitiveWithZero(y: Nat, z: Nat) requires LessThan(Zero, y) requires LessThan(y, z) ensures LessThan(Zero, z) { if !LessThan(Zero, z) { assert z != Zero; assert Zero.S?; assert false; } } /* * Since now the base case of transitive LessThan with Zero is proven, we can now prove using induction. * * In this case, the induction decreases on all three variables, all x, y, z until the base case. */ lemma {:induction x, y, z} LessThanIsTransitive(x: Nat, y: Nat, z: Nat) requires LessThan(x, y) requires LessThan(y, z) ensures LessThan(x, z) decreases x { match x case Zero => LessThanIsTransitiveWithZero(y, z); case S(x') => match y case S(y') => match z case S(z') => LessThanIsTransitive(x', y', z'); } /// Task 3: Define the parametric lists as an algebraic data type /* * Being an inductive data type, it's required that we have a base case constructor and an inductive one. * The inductive Append constructor takes as input a Nat, the head, and a tail, the rest of the list. */ datatype List<T> = Nil | Append(head: T, tail: List) // Exercise (a): defining the size of a list (using natural numbers defined above) /* * We are modelling the function as a recursive one. * The size of an empty list (Nil) is Zero. * * The size of a non-empty list is the successor of the size of the list's tail. */ function Size(l: List<Nat>): Nat decreases l { if l.Nil? then Zero else S(Size(l.tail)) } // Exercise (b): defining the concatenation of two lists /* * Concatenation with an empty list yields the other list. * * The function recursively calculates the result of the concatenation. */ function Concatenation(l1: List<Nat>, l2: List<Nat>) : List<Nat> decreases l1, l2 { match l1 case Nil => l2 case Append(head1, tail1) => match l2 case Nil => l1 case Append(_, _) => Append(head1, Concatenation(tail1, l2)) } // Exercise (c): proving that the size of the concatenation of two lists is the sum of the lists' sizes /* * Starting with a base case in which the first list is empty, the proof is trivial, given ZeroAddNeutral. * Afterwards, the induction follows the next step and matches the second list. * If the list is empty, the result will be, of course, the first list. * Otherwise, an element is discarded from both (the heads), and the verification continues on the tails. */ lemma {:induction l1, l2} SizeOfConcatenationIsSumOfSizes(l1: List<Nat>, l2: List<Nat>) ensures Size(Concatenation(l1, l2)) == Add(Size(l1), Size(l2)) decreases l1, l2 { match l1 case Nil => { ZeroAddNeutral(Size(l2)); assert Size(Concatenation(l1, l2)) == Size(Concatenation(Nil, l2)) == Size(l2) == // ZeroAddNeutral Add(Zero, Size(l2)) == Add(Size(l1), Size(l2)); } case Append(_, tail1) => match l2 case Nil => { assert Size(Concatenation(l1, l2)) == Size(Concatenation(l1, Nil)) == Size(l1) == Add(Size(l1), Zero) == Add(Size(l1), Size(l2)); } case Append(_, tail2) => SizeOfConcatenationIsSumOfSizes(tail1, tail2); } // Exercise (d): defining a function reversing a list /* * The base case is, again, the empty list. * When the list is empty, the reverse of the list is also Nil. * * When dealing with a non-empty list, we make use of the Concatenation operation. * The Reverse of the list will be a concatenation between the reverse of the tail and the head. * Since the head is not a list on its own, a list is created using the Append constructor. */ function ReverseList(l: List<Nat>) : List<Nat> decreases l { if l.Nil? then Nil else Concatenation(ReverseList(l.tail), Append(l.head, Nil)) } // Exercise (e): proving that reversing a list twice we obtain the initial list. /* * Given that during the induction we need to make use of this property, * we first save the result of reversing a concatenation between a list and a single element. * * Aside from the base case, proven with chained equality assertions, the proof follows an inductive approach as well. */ lemma {:induction l, n} ReversalOfConcatenationWithHead(l: List<Nat>, n: Nat) ensures ReverseList(Concatenation(l, Append(n, Nil))) == Append(n, ReverseList(l)) decreases l, n { match l case Nil => { assert ReverseList(Concatenation(l, Append(n, Nil))) == ReverseList(Concatenation(Nil, Append(n, Nil))) == ReverseList(Append(n, Nil)) == Concatenation(ReverseList(Append(n, Nil).tail), Append(Append(n, Nil).head, Nil)) == Concatenation(ReverseList(Nil), Append(n, Nil)) == Concatenation(Nil, Append(n, Nil)) == Append(n, Nil) == Append(n, l) == Append(n, ReverseList(l)); } case Append(head, tail) => ReversalOfConcatenationWithHead(tail, n); } /* * The induction starts with the base case, which is trivial. * * For the inductive steps, there is a need for the property proven above. * Once the property is guaranteed, the chained assertions lead to the solution. */ lemma {:induction l} DoubleReversalResultsInInitialList(l: List<Nat>) ensures l == ReverseList(ReverseList(l)) { match l case Nil => { assert ReverseList(ReverseList(l)) == ReverseList(ReverseList(Nil)) == ReverseList(Nil) == Nil; assert l == ReverseList(ReverseList(l)); } case Append(head, tail) => { ReversalOfConcatenationWithHead(ReverseList(tail), head); assert ReverseList(ReverseList(l)) == ReverseList(ReverseList(Append(head, tail))) == ReverseList(Concatenation(ReverseList(tail), Append(head, Nil))) == // ReversalOfConcatenationWithHead Append(head, ReverseList(ReverseList(tail))) == Append(head, tail) == l; } }
/* * Task 2: Define the natural numbers as an algebraic data type * * Being an inductive data type, it's required that we have a base case constructor and an inductive one. */ datatype Nat = Zero | S(Pred: Nat) /// Task 2 // Exercise (a'): proving that the successor constructor is injective /* * It's known that the successors are equal. * It's know that for equal inputs, a non-random function returns the same result. * Thus, the predecessors of the successors, namely, the numbers themselves, are equal. */ lemma SIsInjective(x: Nat, y: Nat) ensures S(x) == S(y) ==> x == y { assume S(x) == S(y); } // Exercise (a''): Zero is different from successor(x), for any x /* * For all x: Nat, S(x) is built using the S constructor, implying that S(x).Zero? is inherently false. */ lemma ZeroIsDifferentFromSuccessor(n: Nat) ensures S(n) != Zero { } // Exercise (b): inductively defining the addition of natural numbers /* * The function decreases y until it reaches the base inductive case. * The Addition between Zero and a x: Nat will be x. * The Addition between a successor of a y': Nat and another x: Nat is the successor of the Addition between y' and x * * x + y = 1 + ((x - 1) + y) */ function Add(x: Nat, y: Nat) : Nat { match y case Zero => x case S(y') => S(Add(x, y')) } // Exercise (c'): proving that the addition is commutative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Neutral. */ lemma {:induction n} ZeroAddNeutral(n: Nat) ensures Add(n, Zero) == Add(Zero, n) == n { match n case Zero => { == Add(Zero, Zero) == Add(Zero, n) == n; } case S(n') => { == Add(S(n'), Zero) == S(n') == Add(Zero, S(n')) == Add(Zero, n) == n; } } /* * Since Zero is neutral, it is trivial that the order of addition is not of importance. */ lemma {:induction n} ZeroAddCommutative(n: Nat) ensures Add(Zero, n) == Add(n, Zero) { == n == Add(n, Zero); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddCommutative(x: Nat, y: Nat) ensures Add(x, y) == Add(y, x) { match x case Zero => ZeroAddCommutative(y); case S(x') => AddCommutative(x', y); } // Exercise (c''): proving that the addition is associative /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that the Addition with Zero is Associative. * * Again, given that addition with Zero is neutral, the order of calculations is irrelevant. */ lemma {:induction x, y} ZeroAddAssociative(x: Nat, y: Nat) ensures Add(Add(Zero, x), y) == Add(Zero, Add(x, y)) { ZeroAddNeutral(x); == // ZeroAddNeutral Add(x, y) == Add(Zero, Add(x, y)); } /* * Since now the base case of commutative addition with Zero is proven, we can now prove using induction. */ lemma {:induction x, y} AddAssociative(x: Nat, y: Nat, z: Nat) ensures Add(Add(x, y), z) == Add(x, Add(y, z)) { match z case Zero => ZeroAddAssociative(Add(x, y), Zero); case S(z') => AddAssociative(x, y, z'); } // Exercise (d): defining a predicate lt(m, n) that holds when m is less than n /* * If x is Zero and y is a Successor, given that we have proven ZeroIsDifferentFromSuccessor for all x, the predicate holds. * Otherwise, if both are successors, we inductively check their predecessors. */ predicate LessThan(x: Nat, y: Nat) { (x.Zero? && y.S?) || (x.S? && y.S? && LessThan(x.Pred, y.Pred)) } // Exercise (e): proving that lt is transitive /* * It is necessary, as with any induction, to have a proven base case. * In this case, we first prove that LessThan is Transitive having a Zero as the left-most parameter. * * We prove this statement using Reductio Ad Absurdum. * We suppose that Zero is not smaller that an arbitrary z that is non-Zero. * This would imply that Zero has to be a Successor (i.e. Zero.S? == true). * This is inherently false. */ lemma {:induction y, z} LessThanIsTransitiveWithZero(y: Nat, z: Nat) requires LessThan(Zero, y) requires LessThan(y, z) ensures LessThan(Zero, z) { if !LessThan(Zero, z) { } } /* * Since now the base case of transitive LessThan with Zero is proven, we can now prove using induction. * * In this case, the induction decreases on all three variables, all x, y, z until the base case. */ lemma {:induction x, y, z} LessThanIsTransitive(x: Nat, y: Nat, z: Nat) requires LessThan(x, y) requires LessThan(y, z) ensures LessThan(x, z) { match x case Zero => LessThanIsTransitiveWithZero(y, z); case S(x') => match y case S(y') => match z case S(z') => LessThanIsTransitive(x', y', z'); } /// Task 3: Define the parametric lists as an algebraic data type /* * Being an inductive data type, it's required that we have a base case constructor and an inductive one. * The inductive Append constructor takes as input a Nat, the head, and a tail, the rest of the list. */ datatype List<T> = Nil | Append(head: T, tail: List) // Exercise (a): defining the size of a list (using natural numbers defined above) /* * We are modelling the function as a recursive one. * The size of an empty list (Nil) is Zero. * * The size of a non-empty list is the successor of the size of the list's tail. */ function Size(l: List<Nat>): Nat { if l.Nil? then Zero else S(Size(l.tail)) } // Exercise (b): defining the concatenation of two lists /* * Concatenation with an empty list yields the other list. * * The function recursively calculates the result of the concatenation. */ function Concatenation(l1: List<Nat>, l2: List<Nat>) : List<Nat> { match l1 case Nil => l2 case Append(head1, tail1) => match l2 case Nil => l1 case Append(_, _) => Append(head1, Concatenation(tail1, l2)) } // Exercise (c): proving that the size of the concatenation of two lists is the sum of the lists' sizes /* * Starting with a base case in which the first list is empty, the proof is trivial, given ZeroAddNeutral. * Afterwards, the induction follows the next step and matches the second list. * If the list is empty, the result will be, of course, the first list. * Otherwise, an element is discarded from both (the heads), and the verification continues on the tails. */ lemma {:induction l1, l2} SizeOfConcatenationIsSumOfSizes(l1: List<Nat>, l2: List<Nat>) ensures Size(Concatenation(l1, l2)) == Add(Size(l1), Size(l2)) { match l1 case Nil => { ZeroAddNeutral(Size(l2)); == Size(Concatenation(Nil, l2)) == Size(l2) == // ZeroAddNeutral Add(Zero, Size(l2)) == Add(Size(l1), Size(l2)); } case Append(_, tail1) => match l2 case Nil => { == Size(Concatenation(l1, Nil)) == Size(l1) == Add(Size(l1), Zero) == Add(Size(l1), Size(l2)); } case Append(_, tail2) => SizeOfConcatenationIsSumOfSizes(tail1, tail2); } // Exercise (d): defining a function reversing a list /* * The base case is, again, the empty list. * When the list is empty, the reverse of the list is also Nil. * * When dealing with a non-empty list, we make use of the Concatenation operation. * The Reverse of the list will be a concatenation between the reverse of the tail and the head. * Since the head is not a list on its own, a list is created using the Append constructor. */ function ReverseList(l: List<Nat>) : List<Nat> { if l.Nil? then Nil else Concatenation(ReverseList(l.tail), Append(l.head, Nil)) } // Exercise (e): proving that reversing a list twice we obtain the initial list. /* * Given that during the induction we need to make use of this property, * we first save the result of reversing a concatenation between a list and a single element. * * Aside from the base case, proven with chained equality assertions, the proof follows an inductive approach as well. */ lemma {:induction l, n} ReversalOfConcatenationWithHead(l: List<Nat>, n: Nat) ensures ReverseList(Concatenation(l, Append(n, Nil))) == Append(n, ReverseList(l)) { match l case Nil => { == ReverseList(Concatenation(Nil, Append(n, Nil))) == ReverseList(Append(n, Nil)) == Concatenation(ReverseList(Append(n, Nil).tail), Append(Append(n, Nil).head, Nil)) == Concatenation(ReverseList(Nil), Append(n, Nil)) == Concatenation(Nil, Append(n, Nil)) == Append(n, Nil) == Append(n, l) == Append(n, ReverseList(l)); } case Append(head, tail) => ReversalOfConcatenationWithHead(tail, n); } /* * The induction starts with the base case, which is trivial. * * For the inductive steps, there is a need for the property proven above. * Once the property is guaranteed, the chained assertions lead to the solution. */ lemma {:induction l} DoubleReversalResultsInInitialList(l: List<Nat>) ensures l == ReverseList(ReverseList(l)) { match l case Nil => { == ReverseList(ReverseList(Nil)) == ReverseList(Nil) == Nil; } case Append(head, tail) => { ReversalOfConcatenationWithHead(ReverseList(tail), head); == ReverseList(ReverseList(Append(head, tail))) == ReverseList(Concatenation(ReverseList(tail), Append(head, Nil))) == // ReversalOfConcatenationWithHead Append(head, ReverseList(ReverseList(tail))) == Append(head, tail) == l; } }
208
FMSE-2022-2023_tmp_tmp6_x_ba46_Lab3_Lab3.dfy
/* * Task 2: Define in Dafny the conatural numbers as a coinductive datatype * * Being a coinductive data type, it's required that we have a base case constructor and an inductive one * (as is the case with inductive ones as well) */ codatatype Conat = Zero | Succ(Pred: Conat) // Exercise (a): explain why the following coinductive property does NOT hold // lemma ConstructorConat(n: Conat) // ensures n != Succ(n) // { // the following coinductive property does not hold because coinductive datatypes, as opposed to normal datatypes, // are designed for infinite domains, as such, it is improper to test the equality above when dealing with infinity // } // Exercise (b): show that the constructor successor is injective greatest lemma ConstructorInjective(x: Conat, y: Conat) ensures Succ(x) == Succ(y) ==> x == y { assume Succ(x) == Succ(y); assert Succ(x).Pred == Succ(y).Pred; assert x == y; } // Exercise (c): define the ∞ constant (as a corecursive function) // We use a co-recursive call using the Succ constructor on the result, producing an infinite call stack function inf(n: Conat): Conat { Succ(inf(n)) } // Exercise (d): define the addition of conaturals // Similar to add function over the Nat datatype (See Lab2) function add(x: Conat, y: Conat) : Conat { match x case Zero => y case Succ(x') => Succ(add(x', y)) } // Exercise (e): show that by adding ∞ to itself it remains unchanged // Because the focus is on greatest fixed-point we need to use a co-predicate // Aptly renamed to greatest predicate greatest predicate InfinityAddition() { add(inf(Zero), inf(Zero)) == inf(Zero) } // Task 3: Define the parametric streams as a coinductive datatype where s ranges over streams codatatype Stream<A> = Cons(head: A, tail: Stream<A>) // Exercise (a): corecursively define the pointwise addition of two streams of integers // After performing the addition of the value in the heads, proceed similarly with the tails function addition(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head + b.head, addition(a.tail, b.tail)) } // Exercise (b): define a parametric integer constant stream // An infinite stream with the same value function cnst(a: int): Stream<int> { Cons(a, cnst(a)) } // Exercise (c): prove by coinduction that add(s, cnst(0)) = s; // The proof tried below is not complete, however, by telling Dafny that we are dealing with a colemma, // Aptly renamed to greatest lemma, it is able to reason and prove the post-condition by itself greatest lemma additionWithZero(a : Stream<int>) ensures addition(a, cnst(0)) == a { // assert addition(a, cnst(0)) // == // Cons(a.head + cnst(0).head, addition(a.tail, cnst(0).tail)) // == // Cons(a.head + 0, addition(a.tail, cnst(0))) // == // Cons(a.head, addition(a.tail, cnst(0))) // == // Cons(a.head, a.tail) // == // a; } // Exercise (d): define coinductively the predicate greatest predicate leq(a: Stream<int>, b: Stream<int>) { a.head <= b.head && ((a.head == b.head) ==> leq(a.tail, b.tail)) } // Exercise (e): (e) define the stream blink function blink(): Stream<int> { Cons(0, Cons(1, blink())) } // Exercise (f): prove by coinduction that leq(cnst(0), blink) lemma CnstZeroLeqBlink() ensures leq(cnst(0), blink()) { } // Exercise (g): define a function that ”zips” two streams // A stream formed by alternating the elements of both streams one by one function zip(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head, Cons(b.head, zip(a.tail, b.tail))) } // Exercise (h): prove that zipping cnst(0) and cnst(1) yields blink // By using a greatest lemma, Dafny can reason on its own greatest lemma ZipCnstZeroCnstOneEqualsBlink() ensures zip(cnst(0), cnst(1)) == blink() { // assert zip(cnst(0), cnst(1)) // == // Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0), cnst(1)))) // == // Cons(0, Cons(1, Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0), cnst(1)))))) // == // blink(); }
/* * Task 2: Define in Dafny the conatural numbers as a coinductive datatype * * Being a coinductive data type, it's required that we have a base case constructor and an inductive one * (as is the case with inductive ones as well) */ codatatype Conat = Zero | Succ(Pred: Conat) // Exercise (a): explain why the following coinductive property does NOT hold // lemma ConstructorConat(n: Conat) // ensures n != Succ(n) // { // the following coinductive property does not hold because coinductive datatypes, as opposed to normal datatypes, // are designed for infinite domains, as such, it is improper to test the equality above when dealing with infinity // } // Exercise (b): show that the constructor successor is injective greatest lemma ConstructorInjective(x: Conat, y: Conat) ensures Succ(x) == Succ(y) ==> x == y { assume Succ(x) == Succ(y); } // Exercise (c): define the ∞ constant (as a corecursive function) // We use a co-recursive call using the Succ constructor on the result, producing an infinite call stack function inf(n: Conat): Conat { Succ(inf(n)) } // Exercise (d): define the addition of conaturals // Similar to add function over the Nat datatype (See Lab2) function add(x: Conat, y: Conat) : Conat { match x case Zero => y case Succ(x') => Succ(add(x', y)) } // Exercise (e): show that by adding ∞ to itself it remains unchanged // Because the focus is on greatest fixed-point we need to use a co-predicate // Aptly renamed to greatest predicate greatest predicate InfinityAddition() { add(inf(Zero), inf(Zero)) == inf(Zero) } // Task 3: Define the parametric streams as a coinductive datatype where s ranges over streams codatatype Stream<A> = Cons(head: A, tail: Stream<A>) // Exercise (a): corecursively define the pointwise addition of two streams of integers // After performing the addition of the value in the heads, proceed similarly with the tails function addition(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head + b.head, addition(a.tail, b.tail)) } // Exercise (b): define a parametric integer constant stream // An infinite stream with the same value function cnst(a: int): Stream<int> { Cons(a, cnst(a)) } // Exercise (c): prove by coinduction that add(s, cnst(0)) = s; // The proof tried below is not complete, however, by telling Dafny that we are dealing with a colemma, // Aptly renamed to greatest lemma, it is able to reason and prove the post-condition by itself greatest lemma additionWithZero(a : Stream<int>) ensures addition(a, cnst(0)) == a { // assert addition(a, cnst(0)) // == // Cons(a.head + cnst(0).head, addition(a.tail, cnst(0).tail)) // == // Cons(a.head + 0, addition(a.tail, cnst(0))) // == // Cons(a.head, addition(a.tail, cnst(0))) // == // Cons(a.head, a.tail) // == // a; } // Exercise (d): define coinductively the predicate greatest predicate leq(a: Stream<int>, b: Stream<int>) { a.head <= b.head && ((a.head == b.head) ==> leq(a.tail, b.tail)) } // Exercise (e): (e) define the stream blink function blink(): Stream<int> { Cons(0, Cons(1, blink())) } // Exercise (f): prove by coinduction that leq(cnst(0), blink) lemma CnstZeroLeqBlink() ensures leq(cnst(0), blink()) { } // Exercise (g): define a function that ”zips” two streams // A stream formed by alternating the elements of both streams one by one function zip(a: Stream<int>, b: Stream<int>): Stream<int> { Cons(a.head, Cons(b.head, zip(a.tail, b.tail))) } // Exercise (h): prove that zipping cnst(0) and cnst(1) yields blink // By using a greatest lemma, Dafny can reason on its own greatest lemma ZipCnstZeroCnstOneEqualsBlink() ensures zip(cnst(0), cnst(1)) == blink() { // assert zip(cnst(0), cnst(1)) // == // Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))) // == // Cons(0, Cons(1, zip(cnst(0), cnst(1)))) // == // Cons(0, Cons(1, Cons(cnst(0).head, Cons(cnst(1).head, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0).tail, cnst(1).tail))))) // == // Cons(0, Cons(1, Cons(0, Cons(1, zip(cnst(0), cnst(1)))))) // == // blink(); }
209
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise3_Increment_Array.dfy
method incrementArray(a:array<int>) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1 modifies a { var j : int := 0; while(j < a.Length) invariant 0 <= j <= a.Length invariant forall i :: j <= i < a.Length ==> a[i] == old(a[i]) invariant forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1 decreases a.Length - j { assert forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1; assert a[j] == old(a[j]); a[j] := a[j] + 1; assert forall i :: 0 <= i < j ==> a[i] == old(a[i]) + 1; assert a[j] == old(a[j]) + 1; j := j+1; } }
method incrementArray(a:array<int>) requires a.Length > 0 ensures forall i :: 0 <= i < a.Length ==> a[i] == old(a[i]) + 1 modifies a { var j : int := 0; while(j < a.Length) { a[j] := a[j] + 1; j := j+1; } }
210
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise4_Find_Max.dfy
method findMax(a:array<int>) returns (pos:int, maxVal: int) requires a.Length > 0; requires forall i :: 0 <= i < a.Length ==> a[i] >= 0; ensures forall i :: 0 <= i < a.Length ==> a[i] <= maxVal; ensures exists i :: 0 <= i < a.Length && a[i] == maxVal; ensures 0 <= pos < a.Length ensures a[pos] == maxVal; { pos := 0; maxVal := a[0]; var j := 1; while(j < a.Length) invariant 1 <= j <= a.Length; invariant forall i :: 0 <= i < j ==> a[i] <= maxVal; invariant exists i :: 0 <= i < j && a[i] == maxVal; invariant 0 <= pos < a.Length; invariant a[pos] == maxVal; { if (a[j] > maxVal) { maxVal := a[j]; pos := j; } j := j+1; } return; }
method findMax(a:array<int>) returns (pos:int, maxVal: int) requires a.Length > 0; requires forall i :: 0 <= i < a.Length ==> a[i] >= 0; ensures forall i :: 0 <= i < a.Length ==> a[i] <= maxVal; ensures exists i :: 0 <= i < a.Length && a[i] == maxVal; ensures 0 <= pos < a.Length ensures a[pos] == maxVal; { pos := 0; maxVal := a[0]; var j := 1; while(j < a.Length) { if (a[j] > maxVal) { maxVal := a[j]; pos := j; } j := j+1; } return; }
211
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Exercise6_Binary_Search.dfy
method binarySearch(a:array<int>, val:int) returns (pos:int) requires a.Length > 0 requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures 0 <= pos < a.Length ==> a[pos] == val ensures pos < 0 || pos >= a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] != val { var left := 0; var right := a.Length; if a[left] > val || a[right-1] < val { return -1; } while left < right invariant 0 <= left <= right <= a.Length invariant forall i :: 0 <= i < a.Length && !(left <= i < right) ==> a[i] != val decreases right - left { var med := (left + right) / 2; assert left <= med <= right; if a[med] < val { left := med + 1; } else if a[med] > val { right := med; } else { assert a[med] == val; pos := med; return; } } return -1; }
method binarySearch(a:array<int>, val:int) returns (pos:int) requires a.Length > 0 requires forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures 0 <= pos < a.Length ==> a[pos] == val ensures pos < 0 || pos >= a.Length ==> forall i :: 0 <= i < a.Length ==> a[i] != val { var left := 0; var right := a.Length; if a[left] > val || a[right-1] < val { return -1; } while left < right { var med := (left + right) / 2; if a[med] < val { left := med + 1; } else if a[med] > val { right := med; } else { pos := med; return; } } return -1; }
212
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Insertion_Sort_Normal.dfy
predicate sorted (a: array<int>) reads a { sortedA(a, a.Length) } predicate sortedA (a: array<int>, i: int) requires 0 <= i <= a.Length reads a { forall k :: 0 < k < i ==> a[k-1] <= a[k] } method lookForMin (a: array<int>, i: int) returns (m: int) requires 0 <= i < a.Length ensures i <= m < a.Length ensures forall k :: i <= k < a.Length ==> a[k] >= a[m] { var j := i; m := i; while(j < a.Length) invariant i <= j <= a.Length invariant i <= m < a.Length invariant forall k :: i <= k < j ==> a[k] >= a[m] decreases a.Length - j { if(a[j] < a[m]) { m := j; } j := j + 1; } } method insertionSort (a: array<int>) modifies a ensures sorted(a) { var c := 0; while(c < a.Length) invariant 0 <= c <= a.Length invariant forall k, l :: 0 <= k < c <= l < a.Length ==> a[k] <= a[l] invariant sortedA(a, c) { var m := lookForMin(a, c); a[m], a[c] := a[c], a[m]; assert forall k :: c <= k < a.Length ==> a[k] >= a[c]; c := c + 1; } }
predicate sorted (a: array<int>) reads a { sortedA(a, a.Length) } predicate sortedA (a: array<int>, i: int) requires 0 <= i <= a.Length reads a { forall k :: 0 < k < i ==> a[k-1] <= a[k] } method lookForMin (a: array<int>, i: int) returns (m: int) requires 0 <= i < a.Length ensures i <= m < a.Length ensures forall k :: i <= k < a.Length ==> a[k] >= a[m] { var j := i; m := i; while(j < a.Length) { if(a[j] < a[m]) { m := j; } j := j + 1; } } method insertionSort (a: array<int>) modifies a ensures sorted(a) { var c := 0; while(c < a.Length) { var m := lookForMin(a, c); a[m], a[c] := a[c], a[m]; c := c + 1; } }
213
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Insertion_Sorted_Standard.dfy
predicate InsertionSorted(Array: array<int>, left: int, right: int) requires 0 <= left <= right <= Array.Length reads Array { forall i,j :: left <= i < j < right ==> Array[i] <= Array[j] } method sorting(Array: array<int>) requires Array.Length > 1 ensures InsertionSorted(Array, 0, Array.Length) modifies Array { var high := 1; while (high < Array.Length) invariant 1 <= high <= Array.Length invariant InsertionSorted(Array,0,high) { var low := high-1; while low >= 0 && Array[low+1] < Array[low] invariant forall idx,idx' :: 0 <= idx < idx' < high+1 && idx' != low+1 ==> Array[idx] <= Array[idx'] { Array[low], Array[low+1] := Array[low+1], Array[low]; low := low-1; } high := high+1; } }
predicate InsertionSorted(Array: array<int>, left: int, right: int) requires 0 <= left <= right <= Array.Length reads Array { forall i,j :: left <= i < j < right ==> Array[i] <= Array[j] } method sorting(Array: array<int>) requires Array.Length > 1 ensures InsertionSorted(Array, 0, Array.Length) modifies Array { var high := 1; while (high < Array.Length) { var low := high-1; while low >= 0 && Array[low+1] < Array[low] { Array[low], Array[low+1] := Array[low+1], Array[low]; low := low-1; } high := high+1; } }
214
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Merge_Sort.dfy
method mergeSort(a: array<int>) modifies a { sorting(a, 0, a.Length-1); } method merging(a: array<int>, low: int, medium: int, high: int) requires 0 <= low <= medium <= high < a.Length modifies a { var x := 0; var y := 0; var z := 0; var a1: array<int> := new [medium - low + 1]; var a2: array<int> := new [high - medium]; // The first case while(y < a1.Length && low+y < a.Length) invariant 0 <= y <= a1.Length invariant 0 <= low+y <= a.Length decreases a1.Length-y { a1[y] := a[low+y]; y := y +1; } // The second case while(z < a2.Length && medium+z+1 < a.Length) invariant 0 <= z <= a2.Length invariant 0 <= medium+z <= a.Length decreases a2.Length-z { a2[z] := a[medium+z+1]; z := z +1; } y, z := 0, 0; // The third case while (x < high - low + 1 && y <= a1.Length && z <= a2.Length && low+x < a.Length) invariant 0 <= x <= high - low + 1 decreases high-low-x { if(y >= a1.Length && z >= a2.Length) { break; } else if(y >= a1.Length) { a[low+x] := a2[z]; z := z+1; } else if(z >= a2.Length) { a[low+x] := a1[y]; y := y+1; } else { if(a1[y] <= a2[z]) { a[low+x] := a1[y]; y := y +1; } else { a[low+x] := a2[z]; z := z +1; } } x := x+1; } } method sorting(a: array<int>, low: int, high: int) requires 0 <= low && high < a.Length decreases high-low modifies a { if (low < high) { var medium: int := low + (high - low)/2; sorting(a, low, medium); sorting(a, medium+1, high); merging(a, low, medium, high); } }
method mergeSort(a: array<int>) modifies a { sorting(a, 0, a.Length-1); } method merging(a: array<int>, low: int, medium: int, high: int) requires 0 <= low <= medium <= high < a.Length modifies a { var x := 0; var y := 0; var z := 0; var a1: array<int> := new [medium - low + 1]; var a2: array<int> := new [high - medium]; // The first case while(y < a1.Length && low+y < a.Length) { a1[y] := a[low+y]; y := y +1; } // The second case while(z < a2.Length && medium+z+1 < a.Length) { a2[z] := a[medium+z+1]; z := z +1; } y, z := 0, 0; // The third case while (x < high - low + 1 && y <= a1.Length && z <= a2.Length && low+x < a.Length) { if(y >= a1.Length && z >= a2.Length) { break; } else if(y >= a1.Length) { a[low+x] := a2[z]; z := z+1; } else if(z >= a2.Length) { a[low+x] := a1[y]; y := y+1; } else { if(a1[y] <= a2[z]) { a[low+x] := a1[y]; y := y +1; } else { a[low+x] := a2[z]; z := z +1; } } x := x+1; } } method sorting(a: array<int>, low: int, high: int) requires 0 <= low && high < a.Length modifies a { if (low < high) { var medium: int := low + (high - low)/2; sorting(a, low, medium); sorting(a, medium+1, high); merging(a, low, medium, high); } }
215
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Quick_Sort.dfy
predicate quickSorted(Seq: seq<int>) { forall idx_1, idx_2 :: 0 <= idx_1 < idx_2 < |Seq| ==> Seq[idx_1] <= Seq[idx_2] } method threshold(thres:int,Seq:seq<int>) returns (Seq_1:seq<int>,Seq_2:seq<int>) ensures (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres) ensures |Seq_1| + |Seq_2| == |Seq| ensures multiset(Seq_1) + multiset(Seq_2) == multiset(Seq) { Seq_1 := []; Seq_2 := []; var i := 0; while (i < |Seq|) invariant i <= |Seq| invariant (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres) invariant |Seq_1| + |Seq_2| == i invariant multiset(Seq[..i]) == multiset(Seq_1) + multiset(Seq_2) { if (Seq[i] <= thres) { Seq_1 := Seq_1 + [Seq[i]]; } else { Seq_2 := Seq_2 + [Seq[i]]; } assert (Seq[..i] + [Seq[i]]) == Seq[..i+1]; i := i + 1; } assert (Seq[..|Seq|] == Seq); } lemma Lemma_1(Seq_1:seq,Seq_2:seq) // The proof of the lemma is not necessary requires multiset(Seq_1) == multiset(Seq_2) ensures forall x | x in Seq_1 :: x in Seq_2 { forall x | x in Seq_1 ensures x in multiset(Seq_1) { var i := 0; while (i < |Seq_1|) invariant 0 <= i <= |Seq_1| invariant forall idx_1 | 0 <= idx_1 < i :: Seq_1[idx_1] in multiset(Seq_1) { i := i + 1; } } } method quickSort(Seq: seq<int>) returns (Seq': seq<int>) ensures multiset(Seq) == multiset(Seq') decreases |Seq| { if |Seq| == 0 { return []; } else if |Seq| == 1 { return Seq; } else { var Seq_1,Seq_2 := threshold(Seq[0],Seq[1..]); var Seq_1' := quickSort(Seq_1); Lemma_1(Seq_1',Seq_1); var Seq_2' := quickSort(Seq_2); Lemma_1(Seq_2',Seq_2); assert Seq == [Seq[0]] + Seq[1..]; return Seq_1' + [Seq[0]] + Seq_2'; } }
predicate quickSorted(Seq: seq<int>) { forall idx_1, idx_2 :: 0 <= idx_1 < idx_2 < |Seq| ==> Seq[idx_1] <= Seq[idx_2] } method threshold(thres:int,Seq:seq<int>) returns (Seq_1:seq<int>,Seq_2:seq<int>) ensures (forall x | x in Seq_1 :: x <= thres) && (forall x | x in Seq_2 :: x >= thres) ensures |Seq_1| + |Seq_2| == |Seq| ensures multiset(Seq_1) + multiset(Seq_2) == multiset(Seq) { Seq_1 := []; Seq_2 := []; var i := 0; while (i < |Seq|) { if (Seq[i] <= thres) { Seq_1 := Seq_1 + [Seq[i]]; } else { Seq_2 := Seq_2 + [Seq[i]]; } i := i + 1; } } lemma Lemma_1(Seq_1:seq,Seq_2:seq) // The proof of the lemma is not necessary requires multiset(Seq_1) == multiset(Seq_2) ensures forall x | x in Seq_1 :: x in Seq_2 { forall x | x in Seq_1 ensures x in multiset(Seq_1) { var i := 0; while (i < |Seq_1|) { i := i + 1; } } } method quickSort(Seq: seq<int>) returns (Seq': seq<int>) ensures multiset(Seq) == multiset(Seq') { if |Seq| == 0 { return []; } else if |Seq| == 1 { return Seq; } else { var Seq_1,Seq_2 := threshold(Seq[0],Seq[1..]); var Seq_1' := quickSort(Seq_1); Lemma_1(Seq_1',Seq_1); var Seq_2' := quickSort(Seq_2); Lemma_1(Seq_2',Seq_2); return Seq_1' + [Seq[0]] + Seq_2'; } }
216
Final-Project-Dafny_tmp_tmpmcywuqox_Attempts_Selection_Sort_Standard.dfy
method selectionSorted(Array: array<int>) modifies Array ensures multiset(old(Array[..])) == multiset(Array[..]) { var idx := 0; while (idx < Array.Length) invariant 0 <= idx <= Array.Length invariant forall i,j :: 0 <= i < idx <= j < Array.Length ==> Array[i] <= Array[j] invariant forall i,j :: 0 <= i < j < idx ==> Array[i] <= Array[j] invariant multiset(old(Array[..])) == multiset(Array[..]) { var minIndex := idx; var idx' := idx + 1; while (idx' < Array.Length) invariant idx <= idx' <= Array.Length invariant idx <= minIndex < idx' <= Array.Length invariant forall k :: idx <= k < idx' ==> Array[minIndex] <= Array[k] { if (Array[idx'] < Array[minIndex]) { minIndex := idx'; } idx' := idx' + 1; } Array[idx], Array[minIndex] := Array[minIndex], Array[idx]; idx := idx + 1; } }
method selectionSorted(Array: array<int>) modifies Array ensures multiset(old(Array[..])) == multiset(Array[..]) { var idx := 0; while (idx < Array.Length) { var minIndex := idx; var idx' := idx + 1; while (idx' < Array.Length) { if (Array[idx'] < Array[minIndex]) { minIndex := idx'; } idx' := idx' + 1; } Array[idx], Array[minIndex] := Array[minIndex], Array[idx]; idx := idx + 1; } }
217
Final-Project-Dafny_tmp_tmpmcywuqox_Final_Project_3.dfy
method nonZeroReturn(x: int) returns (y: int) ensures y != 0 { if x == 0 { return x + 1; } else { return -x; } } method test() { var input := nonZeroReturn(-1); assert input != 0; }
method nonZeroReturn(x: int) returns (y: int) ensures y != 0 { if x == 0 { return x + 1; } else { return -x; } } method test() { var input := nonZeroReturn(-1); }
218
FlexWeek_tmp_tmpc_tfdj_3_ex2.dfy
// 2. Given an array of positive and negative integers, it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5] function abs(a:int):nat { if a < 0 then -a else a } method aba(a:array<int>)returns (b:array<int>) ensures a.Length == b.Length // needed for next line ensures forall x :: 0<=x<b.Length ==> b[x] == abs(a[x]) { b := new int[a.Length]; var i:=0; while(i < a.Length) invariant 0<= i <= a.Length invariant forall x :: 0<=x<i ==> b[x] == abs(a[x]) { if(a[i] < 0){ b[i] := -a[i]; } else{ b[i] := a[i]; } i := i + 1; } } method Main() { var a := new int[][1,-2,-2,1]; var b := aba(a); assert b[..] == [1,2,2,1]; }
// 2. Given an array of positive and negative integers, it returns an array of the absolute value of all the integers. [-4,1,5,-2,-5]->[4,1,5,2,5] function abs(a:int):nat { if a < 0 then -a else a } method aba(a:array<int>)returns (b:array<int>) ensures a.Length == b.Length // needed for next line ensures forall x :: 0<=x<b.Length ==> b[x] == abs(a[x]) { b := new int[a.Length]; var i:=0; while(i < a.Length) { if(a[i] < 0){ b[i] := -a[i]; } else{ b[i] := a[i]; } i := i + 1; } } method Main() { var a := new int[][1,-2,-2,1]; var b := aba(a); }
219
FlexWeek_tmp_tmpc_tfdj_3_ex3.dfy
method Max(a:array<nat>)returns(m:int) ensures a.Length > 0 ==> forall k :: 0<=k<a.Length ==> m >= a[k]// not strong enough ensures a.Length == 0 ==> m == -1 ensures a.Length > 0 ==> m in a[..] // finally at the top // approach did not work for recusrive function { if(a.Length == 0){ return -1; } assert a.Length > 0; var i := 0; m := a[0]; assert m in a[..]; // had to show that m is in a[..], otherwise how could i assert for it while(i < a.Length) invariant 0<=i<=a.Length invariant forall k :: 0<=k<i ==> m >= a[k]// Not strong enough invariant m in a[..] // again i the array // invariant 0 < i <= a.Length ==> (ret_max(a,i-1) == m) { if(a[i] >= m){ m:= a[i]; } i := i+1; } assert m in a[..]; // } method Checker() { var a := new nat[][1,2,3,50,5,51]; // ghost var a := [1,2,3]; var n := Max(a); // assert a[..] == [1,2,3]; assert n == 51; // assert MAXIMUM(1,2) == 2; // assert ret_max(a,a.Length-1) == 12; // assert ret_max(a,a.Length-1) == x+3; }
method Max(a:array<nat>)returns(m:int) ensures a.Length > 0 ==> forall k :: 0<=k<a.Length ==> m >= a[k]// not strong enough ensures a.Length == 0 ==> m == -1 ensures a.Length > 0 ==> m in a[..] // finally at the top // approach did not work for recusrive function { if(a.Length == 0){ return -1; } var i := 0; m := a[0]; while(i < a.Length) // invariant 0 < i <= a.Length ==> (ret_max(a,i-1) == m) { if(a[i] >= m){ m:= a[i]; } i := i+1; } } method Checker() { var a := new nat[][1,2,3,50,5,51]; // ghost var a := [1,2,3]; var n := Max(a); // assert a[..] == [1,2,3]; // assert MAXIMUM(1,2) == 2; // assert ret_max(a,a.Length-1) == 12; // assert ret_max(a,a.Length-1) == x+3; }
220
FlexWeek_tmp_tmpc_tfdj_3_ex4.dfy
method join(a:array<int>,b:array<int>) returns (c:array<int>) ensures a[..] + b[..] == c[..] ensures multiset(a[..] + b[..]) == multiset(c[..]) ensures multiset(a[..]) + multiset(b[..]) == multiset(c[..]) ensures a.Length+b.Length == c.Length // Forall ensures forall i :: 0<=i<a.Length ==> c[i] == a[i] ensures forall i_2,j_2:: a.Length <= i_2 < c.Length && 0<=j_2< b.Length && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] { c := new int[a.Length+b.Length]; var i:= 0; while(i < a.Length) invariant 0 <= i <=a.Length invariant c[..i] == a[..i] invariant multiset(c[..i]) == multiset(a[..i]) invariant forall k :: 0<=k<i<a.Length ==> c[k] == a[k] { c[i] := a[i]; i := i +1; } i:= a.Length; var j := 0; while(i < c.Length && j<b.Length) // missed j condition invariant 0<=j<=b.Length invariant 0 <= a.Length <= i <= c.Length invariant c[..a.Length] == a[..a.Length] //Sequences invariant c[a.Length..i] == b[..j] // prev loop invariant c[..a.Length] + c[a.Length..i] == a[..a.Length] + b[..j] // prev loop + prev curr loop //Multiset invariant multiset(c[a.Length..i]) == multiset(b[..j]) // prev loop invariant multiset( c[..a.Length] + c[a.Length..i]) == multiset(a[..a.Length] + b[..j]) // prev loop + prev curr loop // Forall invariant forall k :: 0<=k<a.Length ==> c[k] == a[k] // prev loop invariant forall i_2,j_2:: a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] // curr loop invariant forall k_2,i_2,j_2:: 0<=k_2<a.Length && a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] && c[k_2] == a[k_2] // prev loop+curr loop { c[i] := b[j]; i := i +1; j := j +1; } // assert j == b.Length; // assert b[..]==b[..b.Length]; // assert j + a.Length == c.Length; // assert multiset(c[..a.Length]) == multiset(a[..a.Length]); // assert multiset(b[..]) == multiset(b[..j]); // assert multiset(c[a.Length..j+a.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(b[..]); // assert multiset(c[0..c.Length]) == multiset(c[0..a.Length]) + multiset(c[a.Length..c.Length]); // uncomment assert a[..] + b[..] == c[..]; assert multiset(a[..]) + multiset(b[..]) == multiset(c[..]); } method Check(){ var a := new int[][1,2,3]; var b := new int[][4,5]; var c := new int[][1,2,3,4,5]; var d:= join(a,b); assert d[..] == a[..] + b[..]; // works assert multiset(d[..]) == multiset(a[..] + b[..]); assert multiset(d[..]) == multiset(a[..]) + multiset(b[..]); assert d[..] == c[..]; // works assert d[..] == c[..]; //doesn't // print n[..]; }
method join(a:array<int>,b:array<int>) returns (c:array<int>) ensures a[..] + b[..] == c[..] ensures multiset(a[..] + b[..]) == multiset(c[..]) ensures multiset(a[..]) + multiset(b[..]) == multiset(c[..]) ensures a.Length+b.Length == c.Length // Forall ensures forall i :: 0<=i<a.Length ==> c[i] == a[i] ensures forall i_2,j_2:: a.Length <= i_2 < c.Length && 0<=j_2< b.Length && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] { c := new int[a.Length+b.Length]; var i:= 0; while(i < a.Length) { c[i] := a[i]; i := i +1; } i:= a.Length; var j := 0; while(i < c.Length && j<b.Length) // missed j condition //Sequences //Multiset // Forall a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] // curr loop 0<=k_2<a.Length && a.Length <= i_2 < i && 0<=j_2< j && i_2 - j_2 == a.Length ==> c[i_2] == b[j_2] && c[k_2] == a[k_2] // prev loop+curr loop { c[i] := b[j]; i := i +1; j := j +1; } // assert j == b.Length; // assert b[..]==b[..b.Length]; // assert j + a.Length == c.Length; // assert multiset(c[..a.Length]) == multiset(a[..a.Length]); // assert multiset(b[..]) == multiset(b[..j]); // assert multiset(c[a.Length..j+a.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(c[a.Length..c.Length]); // assert multiset(c[a.Length..c.Length]) == multiset(b[..]); // assert multiset(c[0..c.Length]) == multiset(c[0..a.Length]) + multiset(c[a.Length..c.Length]); // uncomment } method Check(){ var a := new int[][1,2,3]; var b := new int[][4,5]; var c := new int[][1,2,3,4,5]; var d:= join(a,b); // print n[..]; }
221
FlexWeek_tmp_tmpc_tfdj_3_reverse.dfy
// Write an *iterative* Dafny method Reverse with signature: // method Reverse(a: array<char>) returns (b: array<char>) // which takes an input array of characters 'a' and outputs array 'b' consisting of // the elements of the input array in reverse order. The following conditions apply: // - the input array cannot be empty // - the input array is not modified // - you must use iteration // - not permitted is an *executable* (parallel) forall statement // - not permitted are any other predicates, functions or methods // For the purposes of this practice exercise, I'll include a test method. method Reverse(a: array<char>) returns (b: array<char>) requires a.Length > 0 ensures a.Length == b.Length ensures forall k :: 0 <= k < a.Length ==> b[k] == a[(a.Length-1) - k]; { b := new char[a.Length]; assert b.Length == a.Length; var i:= 0; while(i < a.Length) invariant 0<=i<=a.Length // invariant 0 < i <= a.Length-1 ==> b[i-1] == a[(a.Length-1) - i+1] // Not good enough invariant forall k :: 0 <= k < i ==> b[k] == a[(a.Length-1) - k] { b[i] := a[(a.Length-1) - i]; i := i + 1; } // assert forall k :: 0 <= k < a.Length ==> a[k] == b[(a.Length-1) - k]; } method Main() { var a := new char[8]; a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r'; var b := Reverse(a); assert b[..] == [ 'r', 'e', 'v', 'e', 'r', 's', 'e', 'd' ]; print b[..]; a := new char[1]; a[0] := '!'; b := Reverse(a); assert b[..] == [ '!' ]; print b[..], '\n'; } // Notice it compiles and the executable generates output (just to see the arrays printed in reverse).
// Write an *iterative* Dafny method Reverse with signature: // method Reverse(a: array<char>) returns (b: array<char>) // which takes an input array of characters 'a' and outputs array 'b' consisting of // the elements of the input array in reverse order. The following conditions apply: // - the input array cannot be empty // - the input array is not modified // - you must use iteration // - not permitted is an *executable* (parallel) forall statement // - not permitted are any other predicates, functions or methods // For the purposes of this practice exercise, I'll include a test method. method Reverse(a: array<char>) returns (b: array<char>) requires a.Length > 0 ensures a.Length == b.Length ensures forall k :: 0 <= k < a.Length ==> b[k] == a[(a.Length-1) - k]; { b := new char[a.Length]; var i:= 0; while(i < a.Length) // invariant 0 < i <= a.Length-1 ==> b[i-1] == a[(a.Length-1) - i+1] // Not good enough { b[i] := a[(a.Length-1) - i]; i := i + 1; } // assert forall k :: 0 <= k < a.Length ==> a[k] == b[(a.Length-1) - k]; } method Main() { var a := new char[8]; a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7] := 'd', 'e', 's', 'r', 'e', 'v', 'e', 'r'; var b := Reverse(a); print b[..]; a := new char[1]; a[0] := '!'; b := Reverse(a); print b[..], '\n'; } // Notice it compiles and the executable generates output (just to see the arrays printed in reverse).
222
Formal-Methods-Project_tmp_tmphh2ar2xv_BubbleSort.dfy
predicate sorted(a: array?<int>, l: int, u: int) reads a; requires a != null; { forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j] } predicate partitioned(a: array?<int>, i: int) reads a requires a != null { forall k, k' :: 0 <= k <= i < k' < a.Length ==> a[k] <= a[k'] } method BubbleSort(a: array?<int>) modifies a requires a != null { var i := a.Length - 1; while(i > 0) invariant sorted(a, i, a.Length-1) invariant partitioned(a, i) { var j := 0; while (j < i) invariant 0 < i < a.Length && 0 <= j <= i invariant sorted(a, i, a.Length-1) invariant partitioned(a, i) invariant forall k :: 0 <= k <= j ==> a[k] <= a[j] { if(a[j] > a[j+1]) { a[j], a[j+1] := a[j+1], a[j]; } j := j + 1; } i := i -1; } } method Main() { var a := new int[5]; a[0], a[1], a[2], a[3], a[4] := 9, 4, 6, 3, 8; BubbleSort(a); var k := 0; while(k < 5) { print a[k], "\n"; k := k+1;} }
predicate sorted(a: array?<int>, l: int, u: int) reads a; requires a != null; { forall i, j :: 0 <= l <= i <= j <= u < a.Length ==> a[i] <= a[j] } predicate partitioned(a: array?<int>, i: int) reads a requires a != null { forall k, k' :: 0 <= k <= i < k' < a.Length ==> a[k] <= a[k'] } method BubbleSort(a: array?<int>) modifies a requires a != null { var i := a.Length - 1; while(i > 0) { var j := 0; while (j < i) { if(a[j] > a[j+1]) { a[j], a[j+1] := a[j+1], a[j]; } j := j + 1; } i := i -1; } } method Main() { var a := new int[5]; a[0], a[1], a[2], a[3], a[4] := 9, 4, 6, 3, 8; BubbleSort(a); var k := 0; while(k < 5) { print a[k], "\n"; k := k+1;} }
223
Formal-Methods-Project_tmp_tmphh2ar2xv_Factorial.dfy
method Fact(x: int) returns (y: int) requires x >= 0; { y := 1; var z := 0; while(z != x) decreases x - z; invariant 0 <= x-z; { z := z + 1; y := y * z; } } method Main() { var a := Fact(87); print a; }
method Fact(x: int) returns (y: int) requires x >= 0; { y := 1; var z := 0; while(z != x) { z := z + 1; y := y * z; } } method Main() { var a := Fact(87); print a; }
224
Formal-Verification-Project_tmp_tmp9gmwsmyp_strings3.dfy
predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |str| < |pre| { return false; } else if pre[..] == str[..|pre|] { return true; } else{ return false; } } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { // Initializing variables var i := 0; res := false; // Check if sub is a prefix of str[i..] and if not, keep incrementing until i = |str| while i <= |str| // Invariant to stay within bounds invariant 0 <= i <= |str| + 1 // Invariant to show that for all j that came before i, no prefix has been found invariant forall j :: (0 <= j < i ==> isNotPrefixPred(sub, str[j..])) // Telling dafny that i is that value that is increasing decreases |str| - i //invariant res <==> isSubstringPred(sub, str) { // Check if the substring is a prefix var temp := isPrefix(sub, str[i..]); // If so, return true as the prefix is a substring of the string if temp == true { return true; } // Otherwise, increment i and try again i := i + 1; } // If we have reached this point, it means that no substring has been found, hence return false return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { // Check that both strings are larger than k if (k > |str1| || k > |str2| ){ return false; } // Initialize variables var i := 0; var temp := false; // Don't want to exceed the bounds of str1 when checking for the element that is k entries away while i <= |str1|-k // Invariant to stay within bounds invariant 0 <= i <= (|str1|-k) + 1 // Invariant to show that when temp is true, it is a substring invariant temp ==> 0 <= i <= (|str1| - k) && isSubstringPred(str1[i..i+k], str2) // Invariant to show that when temp is false, it is not a substring invariant !temp ==> (forall m,n :: (0 <= m < i && n == m+k) ==> isNotSubstringPred(str1[m..n], str2)) // Telling dafny that i is that value that is increasing decreases |str1| - k - i { // Get an index from the array position were are at to the array position that is k away and check the substring temp := isSubstring(str1[i..(i + k)], str2); if temp == true { return true; } i := i + 1; } return false; } lemma haveCommon0SubstringLemma(str1:string, str2:string) ensures haveCommonKSubstringPred(0,str1,str2) { assert isPrefixPred(str1[0..0], str2[0..]); } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var temp := false; var i := |str1|+1; len := i; // Idea is to start the counter at |str1| and decrement until common string is found while i > 0 decreases i // Invariant to stay within bounds invariant 0 <= i <= |str1| + 1 // When temp is true, there is a common sub string of size i invariant temp ==> haveCommonKSubstringPred(i, str1, str2) // When temp is false, there is not a common sub string of size i invariant !temp ==> haveNotCommonKSubstringPred(i, str1, str2) // When temp is false, there is no common sub string of sizes >= i invariant !temp ==> (forall k :: i <= k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) // When temp is true, there is no common sub string of sizes > i invariant temp ==> (forall k :: (i < k <= |str1|) ==> !haveCommonKSubstringPred(k,str1,str2)) { i:= i-1; len := i; temp := haveCommonKSubstring(i, str1, str2); if temp == true { break; } } haveCommon0SubstringLemma(str1, str2); return len; }
predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |str| < |pre| { return false; } else if pre[..] == str[..|pre|] { return true; } else{ return false; } } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { // Initializing variables var i := 0; res := false; // Check if sub is a prefix of str[i..] and if not, keep incrementing until i = |str| while i <= |str| // Invariant to stay within bounds // Invariant to show that for all j that came before i, no prefix has been found // Telling dafny that i is that value that is increasing //invariant res <==> isSubstringPred(sub, str) { // Check if the substring is a prefix var temp := isPrefix(sub, str[i..]); // If so, return true as the prefix is a substring of the string if temp == true { return true; } // Otherwise, increment i and try again i := i + 1; } // If we have reached this point, it means that no substring has been found, hence return false return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { // Check that both strings are larger than k if (k > |str1| || k > |str2| ){ return false; } // Initialize variables var i := 0; var temp := false; // Don't want to exceed the bounds of str1 when checking for the element that is k entries away while i <= |str1|-k // Invariant to stay within bounds // Invariant to show that when temp is true, it is a substring // Invariant to show that when temp is false, it is not a substring // Telling dafny that i is that value that is increasing { // Get an index from the array position were are at to the array position that is k away and check the substring temp := isSubstring(str1[i..(i + k)], str2); if temp == true { return true; } i := i + 1; } return false; } lemma haveCommon0SubstringLemma(str1:string, str2:string) ensures haveCommonKSubstringPred(0,str1,str2) { } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var temp := false; var i := |str1|+1; len := i; // Idea is to start the counter at |str1| and decrement until common string is found while i > 0 // Invariant to stay within bounds // When temp is true, there is a common sub string of size i // When temp is false, there is not a common sub string of size i // When temp is false, there is no common sub string of sizes >= i // When temp is true, there is no common sub string of sizes > i { i:= i-1; len := i; temp := haveCommonKSubstring(i, str1, str2); if temp == true { break; } } haveCommon0SubstringLemma(str1, str2); return len; }
225
Formal-Verification_tmp_tmpuyt21wjt_Dafny_strings1.dfy
predicate isPrefixPredicate(pre: string, str:string) { |str| >= |pre| && pre <= str } method isPrefix(pre: string, str: string) returns (res: bool) ensures |pre| > |str| ==> !res ensures res == isPrefixPredicate(pre, str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| decreases |pre| - i invariant 0 <= i <= |pre| invariant forall j :: 0 <= j < i ==> pre[j] == str[j] { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPredicate (sub: string, str:string) { |str| >= |sub| && (exists i :: 0 <= i <= |str| && isPrefixPredicate(sub, str[i..])) } method isSubstring(sub: string, str: string) returns (res:bool) ensures res == isSubstringPredicate(sub, str) { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 decreases i invariant i >= -1 invariant forall j :: i < j <= |str|-|sub| ==> !(isPrefixPredicate(sub, str[j..])) { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPredicate(k: nat, str1: string, str2: string) { |str1| >= k && |str2| >= k && (exists i :: 0 <= i <= |str1| - k && isSubstringPredicate((str1[i..])[..k], str2)) } method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures |str1| < k || |str2| < k ==> !found ensures haveCommonKSubstringPredicate(k,str1,str2) == found { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 decreases i invariant i >= -1 invariant forall j :: i < j <= |str1| - k ==> !isSubstringPredicate(str1[j..][..k], str2) { var isSub := isSubstring(str1[i..][..k], str2); if isSub { return true; } i := i-1; } return false; } predicate maxCommonSubstringPredicate(str1: string, str2: string, len:nat) { forall k :: len < k <= |str1| ==> !haveCommonKSubstringPredicate(k, str1, str2) } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) ensures len <= |str1| && len <= |str2| ensures len >= 0 ensures maxCommonSubstringPredicate(str1, str2, len) { var i := |str1|; while i > 0 decreases i invariant i >= 0 invariant forall j :: i < j <= |str1| ==> !haveCommonKSubstringPredicate(j, str1, str2) { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } assert i == 0; return 0; }
predicate isPrefixPredicate(pre: string, str:string) { |str| >= |pre| && pre <= str } method isPrefix(pre: string, str: string) returns (res: bool) ensures |pre| > |str| ==> !res ensures res == isPrefixPredicate(pre, str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPredicate (sub: string, str:string) { |str| >= |sub| && (exists i :: 0 <= i <= |str| && isPrefixPredicate(sub, str[i..])) } method isSubstring(sub: string, str: string) returns (res:bool) ensures res == isSubstringPredicate(sub, str) { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPredicate(k: nat, str1: string, str2: string) { |str1| >= k && |str2| >= k && (exists i :: 0 <= i <= |str1| - k && isSubstringPredicate((str1[i..])[..k], str2)) } method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures |str1| < k || |str2| < k ==> !found ensures haveCommonKSubstringPredicate(k,str1,str2) == found { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 { var isSub := isSubstring(str1[i..][..k], str2); if isSub { return true; } i := i-1; } return false; } predicate maxCommonSubstringPredicate(str1: string, str2: string, len:nat) { forall k :: len < k <= |str1| ==> !haveCommonKSubstringPredicate(k, str1, str2) } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) ensures len <= |str1| && len <= |str2| ensures len >= 0 ensures maxCommonSubstringPredicate(str1, str2, len) { var i := |str1|; while i > 0 { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } return 0; }
226
Formal-Verification_tmp_tmpuyt21wjt_Dafny_strings3.dfy
// We spent 2h each on this assignment predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| decreases |pre| - i invariant 0 <= i <= |pre| invariant forall j :: 0 <= j < i ==> pre[j] == str[j] { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 decreases i invariant i >= -1 invariant forall j :: i < j <= |str|-|sub| ==> !(isPrefixPred(sub, str[j..])) { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 decreases i invariant i >= -1 invariant forall j,t :: i < j <= |str1| - k && t==j+k ==> !isSubstringPred(str1[j..t], str2) { var t := i+k; var isSub := isSubstring(str1[i..t], str2); if isSub { return true; } i := i-1; } return false; } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var i := |str1|; while i > 0 decreases i invariant i >= 0 invariant forall j :: i < j <= |str1| ==> !haveCommonKSubstringPred(j, str1, str2) { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } assert i == 0; assert isPrefixPred(str1[0..0],str2[0..]); return 0; }
// We spent 2h each on this assignment predicate isPrefixPred(pre:string, str:string) { (|pre| <= |str|) && pre == str[..|pre|] } predicate isNotPrefixPred(pre:string, str:string) { (|pre| > |str|) || pre != str[..|pre|] } lemma PrefixNegationLemma(pre:string, str:string) ensures isPrefixPred(pre,str) <==> !isNotPrefixPred(pre,str) ensures !isPrefixPred(pre,str) <==> isNotPrefixPred(pre,str) {} method isPrefix(pre: string, str: string) returns (res:bool) ensures !res <==> isNotPrefixPred(pre,str) ensures res <==> isPrefixPred(pre,str) { if |pre| > |str| {return false;} var i := 0; while i < |pre| { if pre[i] != str[i] { return false; } i := i + 1; } return true; } predicate isSubstringPred(sub:string, str:string) { (exists i :: 0 <= i <= |str| && isPrefixPred(sub, str[i..])) } predicate isNotSubstringPred(sub:string, str:string) { (forall i :: 0 <= i <= |str| ==> isNotPrefixPred(sub,str[i..])) } lemma SubstringNegationLemma(sub:string, str:string) ensures isSubstringPred(sub,str) <==> !isNotSubstringPred(sub,str) ensures !isSubstringPred(sub,str) <==> isNotSubstringPred(sub,str) {} method isSubstring(sub: string, str: string) returns (res:bool) ensures res <==> isSubstringPred(sub, str) //ensures !res <==> isNotSubstringPred(sub, str) // This postcondition follows from the above lemma. { if |sub| > |str| { return false; } var i := |str| - |sub|; while i >= 0 { var isPref := isPrefix(sub, str[i..]); if isPref { return true; } i := i-1; } return false; } predicate haveCommonKSubstringPred(k:nat, str1:string, str2:string) { exists i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k && isSubstringPred(str1[i1..j1],str2) } predicate haveNotCommonKSubstringPred(k:nat, str1:string, str2:string) { forall i1, j1 :: 0 <= i1 <= |str1|- k && j1 == i1 + k ==> isNotSubstringPred(str1[i1..j1],str2) } lemma commonKSubstringLemma(k:nat, str1:string, str2:string) ensures haveCommonKSubstringPred(k,str1,str2) <==> !haveNotCommonKSubstringPred(k,str1,str2) ensures !haveCommonKSubstringPred(k,str1,str2) <==> haveNotCommonKSubstringPred(k,str1,str2) {} method haveCommonKSubstring(k: nat, str1: string, str2: string) returns (found: bool) ensures found <==> haveCommonKSubstringPred(k,str1,str2) //ensures !found <==> haveNotCommonKSubstringPred(k,str1,str2) // This postcondition follows from the above lemma. { if( |str1| < k || |str2| < k){ return false; } var i := |str1| - k; while i >= 0 { var t := i+k; var isSub := isSubstring(str1[i..t], str2); if isSub { return true; } i := i-1; } return false; } method maxCommonSubstringLength(str1: string, str2: string) returns (len:nat) requires (|str1| <= |str2|) ensures (forall k :: len < k <= |str1| ==> !haveCommonKSubstringPred(k,str1,str2)) ensures haveCommonKSubstringPred(len,str1,str2) { var i := |str1|; while i > 0 { var ans := haveCommonKSubstring(i, str1, str2); if ans { return i; } i := i -1; } return 0; }
227
Formal-methods-of-software-development_tmp_tmppryvbyty_Bloque 1_Lab3.dfy
method multipleReturns (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures less < x < more method multipleReturns2 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more + less == 2*x // TODO: Hacer en casa method multipleReturns3 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more - less == 2*y function factorial(n:int):int requires n>=0 { if n==0 || n==1 then 1 else n*factorial(n-1) } // PROGRAMA VERIFICADOR DE WHILE method ComputeFact (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { assert 0 <= n <= n && 1*factorial(n) == factorial(n); f:=1; assert 0 <= n <= n && f*factorial(n) == factorial(n); var x:=n; assert 0 <= x <= n && f*factorial(x) == factorial(n); while x > 0 invariant 0 <= x <= n; invariant f*factorial(x)== factorial(n); decreases x-0; { assert 0 <= x-1 <= n && (f*x)*factorial(x-1) == factorial(n); f:= f*x; assert 0 <= x-1 <= n && f*factorial(x-1) == factorial(n); x:=x-1; assert 0 <= x <= n && f*factorial(x) == factorial(n); } assert 0 <= x <= n && f*factorial(x) == factorial(n); } method ComputeFact2 (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { var x:= 0; f:= 1; while x<n invariant 0<=x<=n; invariant f==factorial(x); decreases n - x; { x:=x+1; f:= f*x; assert 0<=x<=n && f==factorial(x); } } // n>=1 ==> 1 + 3 + 5 + ... + (2*n-1) = n*n method Sqare(a:int) returns (x:int) requires a>=1 ensures x == a*a { assert 1==1 && 1 <= 1 <= a; var y:=1; assert y*y==1 && 1 <= y <= a; x:=1; while y < a invariant 1 <= y <= a; invariant y*y==x; { assert (y+1)*(y+1)==x+ (2*(y+1)-1) && 1 <= (y+1) <= a; y:= y+1; assert y*y==x+ (2*y-1) && 1 <= y <= a; x:= x+ (2*y-1); assert y*y==x && 1 <= y <= a; } assert y*y==x && 1 <= y <= a; } function sumSerie(n:int):int requires n >=1 { if n==1 then 1 else sumSerie(n-1) + 2*n -1 } lemma {:induction false} Sqare_Lemma (n:int) requires n>=1 ensures sumSerie(n) == n*n { if n==1 {} else{ Sqare_Lemma(n-1); assert sumSerie(n-1) ==(n-1)*(n-1); calc == { sumSerie(n); sumSerie(n-1) + 2*n -1; { Sqare_Lemma(n-1); assert sumSerie(n-1) ==(n-1)*(n-1); } (n-1)*(n-1) + 2*n -1; n*n-2*n+1 +2*n -1; n*n; } assert sumSerie(n) == n*n; } } method Sqare2(a:int) returns (x:int) requires a>=1 ensures x == a*a { assert 1 <= 1 <= a && 1==1*1; var y:=1; assert 1 <= y <= a && 1==y*y; x:=1; assert 1 <= y <= a && x==y*y; while y < a invariant 1 <= y <= a invariant x==y*y decreases a - y { assert 1 <= (y+1) <= a && (x+2*(y+1)-1)==(y+1)*(y+1); y:= y+1; assert 1 <= y <= a && (x+2*y-1)==y*y; x:= x +2*y -1; assert 1 <= y <= a && x==y*y; } assert 1 <= y <= a && x==y*y; }
method multipleReturns (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures less < x < more method multipleReturns2 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more + less == 2*x // TODO: Hacer en casa method multipleReturns3 (x:int, y:int) returns (more:int, less:int) requires y > 0 ensures more - less == 2*y function factorial(n:int):int requires n>=0 { if n==0 || n==1 then 1 else n*factorial(n-1) } // PROGRAMA VERIFICADOR DE WHILE method ComputeFact (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { f:=1; var x:=n; while x > 0 { f:= f*x; x:=x-1; } } method ComputeFact2 (n:int) returns (f:int) requires n >=0 ensures f== factorial(n) { var x:= 0; f:= 1; while x<n { x:=x+1; f:= f*x; } } // n>=1 ==> 1 + 3 + 5 + ... + (2*n-1) = n*n method Sqare(a:int) returns (x:int) requires a>=1 ensures x == a*a { var y:=1; x:=1; while y < a { y:= y+1; x:= x+ (2*y-1); } } function sumSerie(n:int):int requires n >=1 { if n==1 then 1 else sumSerie(n-1) + 2*n -1 } lemma {:induction false} Sqare_Lemma (n:int) requires n>=1 ensures sumSerie(n) == n*n { if n==1 {} else{ Sqare_Lemma(n-1); calc == { sumSerie(n); sumSerie(n-1) + 2*n -1; { Sqare_Lemma(n-1); } (n-1)*(n-1) + 2*n -1; n*n-2*n+1 +2*n -1; n*n; } } } method Sqare2(a:int) returns (x:int) requires a>=1 ensures x == a*a { var y:=1; x:=1; while y < a { y:= y+1; x:= x +2*y -1; } }
228
Formal-methods-of-software-development_tmp_tmppryvbyty_Bloque 2_Lab6.dfy
/*predicate palindrome<T(==)> (s:seq<T>) { forall i:: 0<=i<|s| ==> s[i] == s[|s|-i-1] } */ // SUM OF A SEQUENCE OF INTEGERS function sum(v: seq<int>): int decreases v { if v==[] then 0 else if |v|==1 then v[0] else v[0]+sum(v[1..]) } /* method vector_Sum(v:seq<int>) returns (x:int) ensures x == sum(v) { var n := 0 ; x := 0; while n != |v| invariant 0 <= n <= |v| invariant x==sum(v[..n]) { assert x == sum(v[..n]) && 0 <= n+1 <= |v|; assert x + v[n] == sum(v[..n])+ v[n] && 0 <= n+1 <= |v|; left_sum_Lemma(v, n+1); assert x + v[n] == sum(v[..n+1]) && 0 <= n+1 <= |v|; x, n := x + v[n], n + 1; assert x==sum(v[..n]) && 0 <= n <= |v|; } assert v== v[..v]; assert sum(v)==sum(v[..n]); assert x == sum(v) && 0 <= n <= |v|; assert x==sum(v[..n]) && 0 <= n <= |v|; } // Structural Induction on Sequences lemma left_sum_Lemma(r:seq<int>, k:int) requires 0 <= k < |r| ensures sum(r[..k]) + r[k] == sum(r[..k+1]); { if |r|==1 || k==0{ assert sum(r[..0])+r[0]== sum(r[..1]); } else { left_sum_Lemma(r[1..], k); assert sum(r[1..][..k]) + r[k] == sum(r[1..][..k+1]); calc { sum(r[..k+1]); sum(r[..k]) + [r[k]]; } } } // MAXIMUM OF A SEQUENCE method maxSeq(v: seq<int>) returns (max:int) requires |v| >= 1 ensures forall i :: 0 <= i < |v| ==> max >= v[i] ensures max in v { max := v[0]; var v' := v[1..]; ghost var t := [v[0]]; while |v'| >= 1 invariant forall i :: 0 <= i < |t| ==> max >= t[i] invariant v == t + v' invariant max in t decreases |v'| - 1 { if v'[0] > max { max := v'[0]; } v', t := v'[1..], t + [v'[0]]; } } // TODO: Hacer // Derivar formalmente un calculo incremental de j*j*j method Cubes (n:int) returns (s:seq<int>) requires n >= 0 ensures |s| == n ensures forall i:int :: 0 <= i < n ==> s[i] == i*i*i { s := []; var c, j, k, m := 0,0,1,6; while j < n invariant 0 <= j ==|s| <= n invariant forall i:int :: 0 <= i < j ==> s[i] == i*i*i invariant c == j*j*j invariant k == 3*j*j + 3*j + 1 invariant m == 6*j + 6 { s := s+[c]; //c := (j+1)*(j+1)*(j+1); c := c + k; k := k + 6*j + 6; m := m + 6; //assert m == 6*(j+1) + 6 == 6*j + 6 + 6; assert k == 3*(j+1)*(j+1) + 3*(j+1) + 1 == 3*j*j + 9*j + 7 == 3*j*j + 3*j + 1 + (6*j + 6); //assert c == (j+1)*(j+1)*(j+1) == j*j*j + 3*j*j + 3*j + 1; j := j+1; //assert m == 6*j + 6; //assert k == 3*j*j + 3*j + 1; //assert c == j*j*j; } } // REVERSE OF A SEQUENCE function reverse<T> (s:seq<T>):seq<T> { if s==[] then [] else reverse(s[1..])+[s[0]] } function seq2set<T> (s:seq<T>): set<T> { if s==[] then {} else {s[0]}+seq2set(s[1..]) } lemma seq2setRev_Lemma<T> (s:seq<T>) ensures seq2set(reverse(s)) == seq2set(s) { if s==[]{} else { seq2setRev_Lemma(s[1..]); assert seq2set(reverse(s[1..])) == seq2set(s[1..]); calc { seq2set(s); seq2set([s[0]]+s[1..]); { concat_seq2set_Lemma([s[0]], s[1..]); assert seq2set([s[0]]+s[1..]) == seq2set([s[0]]) + seq2set(s[1..]); } seq2set([s[0]]) + seq2set(s[1..]); { seq2setRev_Lemma(s[1..]); assert seq2set(reverse(s[1..])) == seq2set(s[1..]); } seq2set([s[0]]) + seq2set(reverse(s[1..])); seq2set(reverse(s[1..])) + seq2set([s[0]]); { concat_seq2set_Lemma(reverse(s[1..]), [s[0]]); } seq2set(reverse(s[1..]) + [s[0]]); { assert reverse([s[0]]+s[1..]) == reverse(s); assert [s[0]]+s[1..] == s; assert reverse(s[1..])+[s[0]] == reverse(s); } seq2set(reverse(s)); } } } lemma concat_seq2set_Lemma<T>(s1:seq<T>,s2:seq<T>) ensures seq2set(s1+s2) == seq2set(s1) + seq2set(s2) { if s1==[]{ assert seq2set(s2) == seq2set([]) + seq2set(s2); assert []==s1; assert []+s2==s2; assert s1+s2==s2; assert seq2set(s1+s2)==seq2set(s2); } else { concat_seq2set_Lemma(s1[1..], s2); assert seq2set(s1[1..]+s2) == seq2set(s1[1..]) + seq2set(s2); calc{ seq2set(s1) + seq2set(s2); seq2set([s1[0]]+s1[1..]) + seq2set(s2); seq2set([s1[0]]) + seq2set(s1[1..]) + seq2set(s2); { concat_seq2set_Lemma(s1[1..], s2); assert seq2set(s1[1..]+s2) == seq2set(s1[1..]) + seq2set(s2); } seq2set([s1[0]]) + seq2set(s1[1..]+s2); { assert s1[1..]+s2 == (s1+s2)[1..]; } seq2set([s1[0]]) + seq2set((s1+s2)[1..]); { // assert seq2set([s1[0]]) + seq2set((s1+s2)[1..]) == seq2set(s1+s2); var ls:= s1+s2; calc { seq2set([s1[0]]) + seq2set((s1+s2)[1..]); seq2set([ls[0]])+ seq2set(ls[1..]); seq2set([ls[0]]+ ls[1..]); seq2set(ls); seq2set(s1+s2); } } seq2set(s1+s2); } } } // REVERSE IS ITS OWN INVERSE lemma Rev_Lemma<T(==)>(s:seq<T>) //ensures forall i :: 0 <= i < |s| ==> s[i] == reverse(s)[|s|-1-i] lemma ItsOwnInverse_Lemma<T> (s:seq<T>) ensures s == reverse(reverse(s)) { if s==[]{} else{ ItsOwnInverse_Lemma(s[1..]); assert s[1..] == reverse(reverse(s[1..])); calc { reverse(reverse(s)); reverse(reverse(s[1..])+[s[0]]); reverse(reverse([s[0]]+s[1..])); { assert reverse([s[0]]+ s[1..]) == reverse(s[1..]) + [s[0]]; assert reverse(reverse([s[0]]+ s[1..])) == reverse(reverse(s[1..]) + [s[0]]); } reverse(reverse(s[1..]) + [s[0]]); { // TODO: Demostrar este assume assume reverse(reverse(s[1..]) + [s[0]]) == [s[0]] + reverse(reverse(s[1..])); } [s[0]] + reverse(reverse(s[1..])); { ItsOwnInverse_Lemma(s[1..]); assert s[1..] == reverse(reverse(s[1..])); } [s[0]]+s[1..]; s; } } } // SCALAR PRODUCT OF TWO VECTORS OF INTEGER function scalar_product (v1:seq<int>, v2:seq<int>):int requires |v1| == |v2| { if v1 == [] then 0 else v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]) } lemma scalar_product_Lemma (v1:seq<int>, v2:seq<int>) requires |v1| == |v2| > 0 ensures scalar_product(v1,v2) == scalar_product(v1[..|v1|-1],v2[..|v2|-1]) + v1[|v1|-1] * v2[|v2|-1] { // INDUCCION EN LA LONGITUD DE V1 if |v1| == 0 && |v2| == 0 {} else if |v1| == 1 {} else { // Se crean estas variables para simplificar las operaciones var v1r:= v1[1..]; var v2r:= v2[1..]; var t1:= |v1[1..]|-1; var t2:= |v2[1..]|-1; // Se realiza la induccion utilizando las variables scalar_product_Lemma(v1r, v2r); assert scalar_product(v1r,v2r) == scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI // Se demuestra que la propiedad se mantiene calc{ scalar_product(v1,v2); v1[0]*v2[0] + scalar_product(v1r, v2r); v1[0]*v2[0] + scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; { scalar_product_Lemma(v1r, v2r); assert scalar_product(v1r,v2r) == scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI } v1[0]*v2[0] + scalar_product(v1r,v2r); v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]); scalar_product(v1,v2); } } } // MULTISETS method multiplicity_examples<T> () { var m := multiset{2,4,6,2,1,3,1,7,1,5,4,7,8,1,6}; assert m[7] == 2; assert m[1] == 4; assert forall m1: multiset<T>, m2 :: m1 == m2 <==> forall z:T :: m1[z] == m2[z]; } // REVERSE HAS THE SAME MULTISET lemma seqMultiset_Lemma<T> (s:seq<T>) ensures multiset(reverse(s)) == multiset(s) { if s==[]{} else { seqMultiset_Lemma(s[1..]); assert multiset(reverse(s[1..])) == multiset(s[1..]); calc { multiset(reverse(s)); multiset(reverse(s[1..]) + [s[0]]); multiset(reverse(s[1..])) + multiset{[s[0]]}; multiset(s[1..]) + multiset{[s[0]]}; multiset(s); } assert multiset(reverse(s)) == multiset(s); } } */ lemma empty_Lemma<T> (r:seq<T>) requires multiset(r) == multiset{} ensures r == [] { if r != [] { assert r[0] in multiset(r); } } lemma elem_Lemma<T> (s:seq<T>,r:seq<T>) requires s != [] && multiset(s) == multiset(r) ensures exists i :: 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); // SEQUENCES WITH EQUAL MULTISETS HAVE EQUAL SUMS lemma sumElems_Lemma(s:seq<int>, r:seq<int>) requires multiset(s) == multiset(r) ensures sum(s) == sum(r) { if s==[]{ empty_Lemma(r); } else { // Con este lema demuestro que el elemento que le quito a s tambien se lo quito a r y de esta manera // poder hacer la induccion elem_Lemma(s,r); var i :| 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); sumElems_Lemma(s[1..], r[..i]+r[i+1..]); assert sum(s[1..]) == sum(r[..i]+r[i+1..]); //HI // Hago la llamada recursiva sumElems_Lemma(s[1..], r[..i]+r[i+1..]); assert sum(s[1..]) == sum(r[..i]+r[i+1..]); calc { sum(s); s[0]+sum(s[1..]); { sumElems_Lemma(s[1..], r[..i]+r[i+1..]); assert sum(s[1..]) == sum(r[..i]+r[i+1..]); } s[0]+sum(r[..i]+r[i+1..]); { assert s[0] == r[i]; } r[i]+sum(r[..i]+r[i+1..]); { // TODO: No consigo acertarlo assume r[i]+sum(r[..i]+r[i+1..]) == sum([r[i]]+r[..i] + r[i+1..]) == sum(r); } sum(r); } } }
/*predicate palindrome<T(==)> (s:seq<T>) { forall i:: 0<=i<|s| ==> s[i] == s[|s|-i-1] } */ // SUM OF A SEQUENCE OF INTEGERS function sum(v: seq<int>): int { if v==[] then 0 else if |v|==1 then v[0] else v[0]+sum(v[1..]) } /* method vector_Sum(v:seq<int>) returns (x:int) ensures x == sum(v) { var n := 0 ; x := 0; while n != |v| { left_sum_Lemma(v, n+1); x, n := x + v[n], n + 1; } } // Structural Induction on Sequences lemma left_sum_Lemma(r:seq<int>, k:int) requires 0 <= k < |r| ensures sum(r[..k]) + r[k] == sum(r[..k+1]); { if |r|==1 || k==0{ } else { left_sum_Lemma(r[1..], k); calc { sum(r[..k+1]); sum(r[..k]) + [r[k]]; } } } // MAXIMUM OF A SEQUENCE method maxSeq(v: seq<int>) returns (max:int) requires |v| >= 1 ensures forall i :: 0 <= i < |v| ==> max >= v[i] ensures max in v { max := v[0]; var v' := v[1..]; ghost var t := [v[0]]; while |v'| >= 1 { if v'[0] > max { max := v'[0]; } v', t := v'[1..], t + [v'[0]]; } } // TODO: Hacer // Derivar formalmente un calculo incremental de j*j*j method Cubes (n:int) returns (s:seq<int>) requires n >= 0 ensures |s| == n ensures forall i:int :: 0 <= i < n ==> s[i] == i*i*i { s := []; var c, j, k, m := 0,0,1,6; while j < n { s := s+[c]; //c := (j+1)*(j+1)*(j+1); c := c + k; k := k + 6*j + 6; m := m + 6; //assert m == 6*(j+1) + 6 == 6*j + 6 + 6; == 3*j*j + 9*j + 7 == 3*j*j + 3*j + 1 + (6*j + 6); //assert c == (j+1)*(j+1)*(j+1) == j*j*j + 3*j*j + 3*j + 1; j := j+1; //assert m == 6*j + 6; //assert k == 3*j*j + 3*j + 1; //assert c == j*j*j; } } // REVERSE OF A SEQUENCE function reverse<T> (s:seq<T>):seq<T> { if s==[] then [] else reverse(s[1..])+[s[0]] } function seq2set<T> (s:seq<T>): set<T> { if s==[] then {} else {s[0]}+seq2set(s[1..]) } lemma seq2setRev_Lemma<T> (s:seq<T>) ensures seq2set(reverse(s)) == seq2set(s) { if s==[]{} else { seq2setRev_Lemma(s[1..]); calc { seq2set(s); seq2set([s[0]]+s[1..]); { concat_seq2set_Lemma([s[0]], s[1..]); } seq2set([s[0]]) + seq2set(s[1..]); { seq2setRev_Lemma(s[1..]); } seq2set([s[0]]) + seq2set(reverse(s[1..])); seq2set(reverse(s[1..])) + seq2set([s[0]]); { concat_seq2set_Lemma(reverse(s[1..]), [s[0]]); } seq2set(reverse(s[1..]) + [s[0]]); { } seq2set(reverse(s)); } } } lemma concat_seq2set_Lemma<T>(s1:seq<T>,s2:seq<T>) ensures seq2set(s1+s2) == seq2set(s1) + seq2set(s2) { if s1==[]{ } else { concat_seq2set_Lemma(s1[1..], s2); calc{ seq2set(s1) + seq2set(s2); seq2set([s1[0]]+s1[1..]) + seq2set(s2); seq2set([s1[0]]) + seq2set(s1[1..]) + seq2set(s2); { concat_seq2set_Lemma(s1[1..], s2); } seq2set([s1[0]]) + seq2set(s1[1..]+s2); { } seq2set([s1[0]]) + seq2set((s1+s2)[1..]); { // assert seq2set([s1[0]]) + seq2set((s1+s2)[1..]) == seq2set(s1+s2); var ls:= s1+s2; calc { seq2set([s1[0]]) + seq2set((s1+s2)[1..]); seq2set([ls[0]])+ seq2set(ls[1..]); seq2set([ls[0]]+ ls[1..]); seq2set(ls); seq2set(s1+s2); } } seq2set(s1+s2); } } } // REVERSE IS ITS OWN INVERSE lemma Rev_Lemma<T(==)>(s:seq<T>) //ensures forall i :: 0 <= i < |s| ==> s[i] == reverse(s)[|s|-1-i] lemma ItsOwnInverse_Lemma<T> (s:seq<T>) ensures s == reverse(reverse(s)) { if s==[]{} else{ ItsOwnInverse_Lemma(s[1..]); calc { reverse(reverse(s)); reverse(reverse(s[1..])+[s[0]]); reverse(reverse([s[0]]+s[1..])); { } reverse(reverse(s[1..]) + [s[0]]); { // TODO: Demostrar este assume assume reverse(reverse(s[1..]) + [s[0]]) == [s[0]] + reverse(reverse(s[1..])); } [s[0]] + reverse(reverse(s[1..])); { ItsOwnInverse_Lemma(s[1..]); } [s[0]]+s[1..]; s; } } } // SCALAR PRODUCT OF TWO VECTORS OF INTEGER function scalar_product (v1:seq<int>, v2:seq<int>):int requires |v1| == |v2| { if v1 == [] then 0 else v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]) } lemma scalar_product_Lemma (v1:seq<int>, v2:seq<int>) requires |v1| == |v2| > 0 ensures scalar_product(v1,v2) == scalar_product(v1[..|v1|-1],v2[..|v2|-1]) + v1[|v1|-1] * v2[|v2|-1] { // INDUCCION EN LA LONGITUD DE V1 if |v1| == 0 && |v2| == 0 {} else if |v1| == 1 {} else { // Se crean estas variables para simplificar las operaciones var v1r:= v1[1..]; var v2r:= v2[1..]; var t1:= |v1[1..]|-1; var t2:= |v2[1..]|-1; // Se realiza la induccion utilizando las variables scalar_product_Lemma(v1r, v2r); scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI // Se demuestra que la propiedad se mantiene calc{ scalar_product(v1,v2); v1[0]*v2[0] + scalar_product(v1r, v2r); v1[0]*v2[0] + scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; { scalar_product_Lemma(v1r, v2r); scalar_product(v1r[..t1],v2r[..t2]) + v1r[t1] * v2r[t2]; //HI } v1[0]*v2[0] + scalar_product(v1r,v2r); v1[0]*v2[0] + scalar_product(v1[1..],v2[1..]); scalar_product(v1,v2); } } } // MULTISETS method multiplicity_examples<T> () { var m := multiset{2,4,6,2,1,3,1,7,1,5,4,7,8,1,6}; } // REVERSE HAS THE SAME MULTISET lemma seqMultiset_Lemma<T> (s:seq<T>) ensures multiset(reverse(s)) == multiset(s) { if s==[]{} else { seqMultiset_Lemma(s[1..]); calc { multiset(reverse(s)); multiset(reverse(s[1..]) + [s[0]]); multiset(reverse(s[1..])) + multiset{[s[0]]}; multiset(s[1..]) + multiset{[s[0]]}; multiset(s); } } } */ lemma empty_Lemma<T> (r:seq<T>) requires multiset(r) == multiset{} ensures r == [] { if r != [] { } } lemma elem_Lemma<T> (s:seq<T>,r:seq<T>) requires s != [] && multiset(s) == multiset(r) ensures exists i :: 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); // SEQUENCES WITH EQUAL MULTISETS HAVE EQUAL SUMS lemma sumElems_Lemma(s:seq<int>, r:seq<int>) requires multiset(s) == multiset(r) ensures sum(s) == sum(r) { if s==[]{ empty_Lemma(r); } else { // Con este lema demuestro que el elemento que le quito a s tambien se lo quito a r y de esta manera // poder hacer la induccion elem_Lemma(s,r); var i :| 0 <= i < |r| && r[i] == s[0] && multiset(s[1..]) == multiset(r[..i]+r[i+1..]); sumElems_Lemma(s[1..], r[..i]+r[i+1..]); // Hago la llamada recursiva sumElems_Lemma(s[1..], r[..i]+r[i+1..]); calc { sum(s); s[0]+sum(s[1..]); { sumElems_Lemma(s[1..], r[..i]+r[i+1..]); } s[0]+sum(r[..i]+r[i+1..]); { } r[i]+sum(r[..i]+r[i+1..]); { // TODO: No consigo acertarlo assume r[i]+sum(r[..i]+r[i+1..]) == sum([r[i]]+r[..i] + r[i+1..]) == sum(r); } sum(r); } } }
229
Formal-methods-of-software-development_tmp_tmppryvbyty_Examenes_Beni_Heusel-Benedikt-Ass-1.dfy
// APELLIDOS: Heusel // NOMBRE: Benedikt // ESPECIALIDAD: ninguna (Erasmus) // ESTÁ PERFECTO, NO HAY NINGUN COMENTARIO MAS ABAJO // EJERCICIO 1 // Demostrar el lemma div10_Lemma por inducción en n // y luego usarlo para demostrar el lemma div10Forall_Lemma function exp (x:int,e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma div10_Lemma (n:nat) requires n >= 3; ensures (exp(3,4*n)+9)%10 == 0 { if n == 3 { //paso base calc { //sólo para mí, comprobado automaticamente (exp(3,4*n)+9); (exp(3,4*3)+9); exp(3, 12) + 9; 531441 + 9; 531450; 10 * 53145; } } else { //paso inductivo div10_Lemma(n-1); //assert (exp(3,4*(n-1))+9)%10 == 0; // HI var k := (exp(3,4*(n-1))+9) / 10; assert 10 * k == (exp(3,4*(n-1))+9); calc { exp(3, 4*n) + 9; 3 * 3 * exp(3,4*n - 2) + 9; 3 * 3 * 3 * 3 * exp(3,4*n - 4) + 9; 81 * exp(3,4*n - 4) + 9; 81 * exp(3,4 * (n-1)) + 9; 80 * exp(3,4 * (n-1)) + (exp(3,4 * (n-1)) + 9); 80 * exp(3,4 * (n-1)) + 10*k; 10 * (8 * exp(3,4 * (n-1)) + k); } } } //Por inducción en n lemma div10Forall_Lemma () ensures forall n :: n>=3 ==> (exp(3,4*n)+9)%10==0 { forall n | n>=3 {div10_Lemma(n);} } //Llamando al lemma anterior // EJERCICIO 2 // Demostrar por inducción en n el lemma de abajo acerca de la función sumSerie que se define primero. // Recuerda que debes JUSTIFICAR como se obtiene la propiedad del ensures a partir de la hipótesis de inducción. function sumSerie (x:int,n:nat):int { if n == 0 then 1 else sumSerie(x,n-1) + exp(x,n) } lemma {:induction false} sumSerie_Lemma (x:int,n:nat) ensures (1-x) * sumSerie(x,n) == 1 - exp(x,n+1) { if n == 0 { //paso base calc { (1-x) * sumSerie(x,n); (1-x) * sumSerie(x,0); (1-x) * 1; 1 - x; 1 - exp(x,1); 1 - exp(x,n+1); } } else{ //paso inductivo calc { (1-x) * sumSerie(x,n); (1-x) * (sumSerie(x,n-1) + exp(x,n)); (1-x) * sumSerie(x,n-1) + (1-x) * exp(x,n); { sumSerie_Lemma(x, n-1); //assert (1-x) * sumSerie(x,n-1) == 1 - exp(x,n); // HI } 1 - exp(x,n) + (1-x) * exp(x,n); 1 - exp(x,n) + exp(x,n) - x * exp(x,n); 1 - x * exp(x,n); 1 - exp(x,n + 1); } } } // EJERCICIO 3 // Probar el lemma noSq_Lemma por contradicción + casos (ver el esquema de abajo). // Se niega la propiedad en el ensures y luego se hacen dos casos (1) z%2 == 0 y (2) z%2 == 1. // En cada uno de los dos casos hay que llegar a probar "assert false" lemma notSq_Lemma (n:int) ensures !exists z :: z*z == 4*n + 2 { //Por contradicción con dos casos: if exists z :: 4*n + 2 == z*z { var z :| z*z == 4*n + 2 == z*z; if z%2 == 0 { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" var k := z/2; assert z == 2*k; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k)*(2*k); 2 * (2*n+1) == 2 * (2*k*k); 2*n+1 == 2*k*k; 2*n+1 == 2*(k*k); } assert 0 == 2*(k*k) % 2 == (2*n+1) % 2 == 1; assert false; } else { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" //assert z % 2 == 1; var k := (z-1) / 2; assert z == 2*k + 1; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k + 1)*(2*k + 1); 4*n + 2 == 4*k*k + 4*k + 1; 4*n + 2 == 2 * (2*k*k + 2*k) + 1; 2 * (2*n + 1) == 2 * (2*k*k + 2*k) + 1; } assert 0 == (2 * (2*n + 1)) % 2 == (2 * (2*k*k + 2*k) + 1) % 2 == 1; assert false; } } } // EJERCICIO 4 //Probar el lemma oneIsEven_Lemma por contradicción, usando también el lemma del EJERCICIO 3. lemma oneIsEven_Lemma (x:int,y:int,z:int) requires z*z == x*x + y*y ensures x%2 == 0 || y%2 == 0 { if !(x%2 == 0 || y%2 == 0) { //assert x%2 == 1 && y%2 == 1; assert x == 2 * ((x-1)/2) + 1; var k: int :| 2*k + 1 == x; assert y == 2 * ((y-1)/2) + 1; var b: int :| 2*b + 1 == y; calc { x*x + y*y; (2*k + 1) * (2*k + 1) + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + 4*b*b + 4*b + 1; 4*k*k + 4*k + 4*b*b + 4*b + 2; 4 * (k*k + k + b*b + b) + 2; } assert z * z == 4 * (k*k + k + b*b + b) + 2; notSq_Lemma(k*k + k + b*b + b); //assert !exists z :: z*z == 4*(k*k + k + b*b + b) + 2; assert false; } } // Por contradicción, y usando notSq_Lemma. ////////////////////////////////////////////////////////////////////////////////////////////// /* ESTE EJERCICIO SÓLO DEBES HACERLO SI HAS CONSEGUIDO DEMOSTRAR CON EXITO LOS EJERCICIOS 1 y 2 EJERCICIO 5 En este ejercicio se dan dos lemma: exp_Lemma y prod_Lemma, que Dafny demuestra automáticamente. Lo que se pide es probar expPlus1_Lemma, por inducción en n, haciendo una calculation con == y >=, que en las pistas (hints) use la HI y también llamadas a esos dos lemas. */ lemma exp_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma prod_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma expPlus1_Lemma(x:int,n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n == 1 { calc { exp(x+1,n); == exp(x+1,1); == x + 1; >= //efectivamente en el caso base tenemos igualdad x + 1; == exp(x,1) + 1; == exp(x,n) + 1; } } else { calc { exp(x+1,n); == (x + 1) * exp(x+1,n-1); >= { expPlus1_Lemma(x, n-1); //assert exp(x+1,n-1) >= exp(x,n-1) + 1; HI //assert exp(x+1,n-1) >= exp(x,n-1) + 1; // HI //aquí se necesitaría tambien prod_lemma, //pero parece que el paso se demuestra tambien //sin la llamada } (x + 1) * (exp(x,n-1) + 1); == x * exp(x,n-1) + x + exp(x,n-1) + 1; == exp(x,n) + x + exp(x,n-1) + 1; == exp(x,n) + 1 + exp(x,n-1) + x; >= { exp_Lemma(x, n-1); } exp(x,n) + 1; } } } // Por inducción en n, y usando exp_Lemma y prod_Lemma.
// APELLIDOS: Heusel // NOMBRE: Benedikt // ESPECIALIDAD: ninguna (Erasmus) // ESTÁ PERFECTO, NO HAY NINGUN COMENTARIO MAS ABAJO // EJERCICIO 1 // Demostrar el lemma div10_Lemma por inducción en n // y luego usarlo para demostrar el lemma div10Forall_Lemma function exp (x:int,e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma div10_Lemma (n:nat) requires n >= 3; ensures (exp(3,4*n)+9)%10 == 0 { if n == 3 { //paso base calc { //sólo para mí, comprobado automaticamente (exp(3,4*n)+9); (exp(3,4*3)+9); exp(3, 12) + 9; 531441 + 9; 531450; 10 * 53145; } } else { //paso inductivo div10_Lemma(n-1); //assert (exp(3,4*(n-1))+9)%10 == 0; // HI var k := (exp(3,4*(n-1))+9) / 10; calc { exp(3, 4*n) + 9; 3 * 3 * exp(3,4*n - 2) + 9; 3 * 3 * 3 * 3 * exp(3,4*n - 4) + 9; 81 * exp(3,4*n - 4) + 9; 81 * exp(3,4 * (n-1)) + 9; 80 * exp(3,4 * (n-1)) + (exp(3,4 * (n-1)) + 9); 80 * exp(3,4 * (n-1)) + 10*k; 10 * (8 * exp(3,4 * (n-1)) + k); } } } //Por inducción en n lemma div10Forall_Lemma () ensures forall n :: n>=3 ==> (exp(3,4*n)+9)%10==0 { forall n | n>=3 {div10_Lemma(n);} } //Llamando al lemma anterior // EJERCICIO 2 // Demostrar por inducción en n el lemma de abajo acerca de la función sumSerie que se define primero. // Recuerda que debes JUSTIFICAR como se obtiene la propiedad del ensures a partir de la hipótesis de inducción. function sumSerie (x:int,n:nat):int { if n == 0 then 1 else sumSerie(x,n-1) + exp(x,n) } lemma {:induction false} sumSerie_Lemma (x:int,n:nat) ensures (1-x) * sumSerie(x,n) == 1 - exp(x,n+1) { if n == 0 { //paso base calc { (1-x) * sumSerie(x,n); (1-x) * sumSerie(x,0); (1-x) * 1; 1 - x; 1 - exp(x,1); 1 - exp(x,n+1); } } else{ //paso inductivo calc { (1-x) * sumSerie(x,n); (1-x) * (sumSerie(x,n-1) + exp(x,n)); (1-x) * sumSerie(x,n-1) + (1-x) * exp(x,n); { sumSerie_Lemma(x, n-1); //assert (1-x) * sumSerie(x,n-1) == 1 - exp(x,n); // HI } 1 - exp(x,n) + (1-x) * exp(x,n); 1 - exp(x,n) + exp(x,n) - x * exp(x,n); 1 - x * exp(x,n); 1 - exp(x,n + 1); } } } // EJERCICIO 3 // Probar el lemma noSq_Lemma por contradicción + casos (ver el esquema de abajo). // Se niega la propiedad en el ensures y luego se hacen dos casos (1) z%2 == 0 y (2) z%2 == 1. // En cada uno de los dos casos hay que llegar a probar "assert false" lemma notSq_Lemma (n:int) ensures !exists z :: z*z == 4*n + 2 { //Por contradicción con dos casos: if exists z :: 4*n + 2 == z*z { var z :| z*z == 4*n + 2 == z*z; if z%2 == 0 { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" var k := z/2; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k)*(2*k); 2 * (2*n+1) == 2 * (2*k*k); 2*n+1 == 2*k*k; 2*n+1 == 2*(k*k); } } else { //llegar aquí a una contradicción y cambiar el "assume false" por "assert false" //assert z % 2 == 1; var k := (z-1) / 2; calc ==> { 4*n + 2 == z*z; 4*n + 2 == (2*k + 1)*(2*k + 1); 4*n + 2 == 4*k*k + 4*k + 1; 4*n + 2 == 2 * (2*k*k + 2*k) + 1; 2 * (2*n + 1) == 2 * (2*k*k + 2*k) + 1; } } } } // EJERCICIO 4 //Probar el lemma oneIsEven_Lemma por contradicción, usando también el lemma del EJERCICIO 3. lemma oneIsEven_Lemma (x:int,y:int,z:int) requires z*z == x*x + y*y ensures x%2 == 0 || y%2 == 0 { if !(x%2 == 0 || y%2 == 0) { //assert x%2 == 1 && y%2 == 1; var k: int :| 2*k + 1 == x; var b: int :| 2*b + 1 == y; calc { x*x + y*y; (2*k + 1) * (2*k + 1) + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + (2*b + 1) * (2*b + 1); 4*k*k + 4*k + 1 + 4*b*b + 4*b + 1; 4*k*k + 4*k + 4*b*b + 4*b + 2; 4 * (k*k + k + b*b + b) + 2; } notSq_Lemma(k*k + k + b*b + b); //assert !exists z :: z*z == 4*(k*k + k + b*b + b) + 2; } } // Por contradicción, y usando notSq_Lemma. ////////////////////////////////////////////////////////////////////////////////////////////// /* ESTE EJERCICIO SÓLO DEBES HACERLO SI HAS CONSEGUIDO DEMOSTRAR CON EXITO LOS EJERCICIOS 1 y 2 EJERCICIO 5 En este ejercicio se dan dos lemma: exp_Lemma y prod_Lemma, que Dafny demuestra automáticamente. Lo que se pide es probar expPlus1_Lemma, por inducción en n, haciendo una calculation con == y >=, que en las pistas (hints) use la HI y también llamadas a esos dos lemas. */ lemma exp_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma prod_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} //NO DEMOSTRAR, USAR PARA PROBAR EL DE ABAJO lemma expPlus1_Lemma(x:int,n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n == 1 { calc { exp(x+1,n); == exp(x+1,1); == x + 1; >= //efectivamente en el caso base tenemos igualdad x + 1; == exp(x,1) + 1; == exp(x,n) + 1; } } else { calc { exp(x+1,n); == (x + 1) * exp(x+1,n-1); >= { expPlus1_Lemma(x, n-1); //assert exp(x+1,n-1) >= exp(x,n-1) + 1; HI //assert exp(x+1,n-1) >= exp(x,n-1) + 1; // HI //aquí se necesitaría tambien prod_lemma, //pero parece que el paso se demuestra tambien //sin la llamada } (x + 1) * (exp(x,n-1) + 1); == x * exp(x,n-1) + x + exp(x,n-1) + 1; == exp(x,n) + x + exp(x,n-1) + 1; == exp(x,n) + 1 + exp(x,n-1) + x; >= { exp_Lemma(x, n-1); } exp(x,n) + 1; } } } // Por inducción en n, y usando exp_Lemma y prod_Lemma.
230
FormalMethods_tmp_tmpvda2r3_o_dafny_Invariants_ex1.dfy
method Mult(x:nat, y:nat) returns (r:nat) ensures r == x * y { // Valores passados por parâmetros são imutáveis var m := x; var n := y; r := 0; // Soma sucessiva para multiplicar dois números. while m > 0 invariant m*n+r == x*y invariant m>=0 { r := r + n; m := m - 1; } return r; // NOT(m>0) ^ Inv ==> r = x*y } /* Inv = m*n + r = x*y Mult(5,3) Teste de mesa x y m n r Inv --> m*n + r = x*y 5 3 5 3 0 5x3+0 = 5*3 5 3 4 3 3 4x3+3 = 5*3 5 3 3 3 6 3x3+6 = 5*3 5 3 2 3 9 2x3+9 = 5*3 5 3 1 3 12 1x3+12 = 5*3 5 3 0 3 15 0x3+15 = 5*3 */
method Mult(x:nat, y:nat) returns (r:nat) ensures r == x * y { // Valores passados por parâmetros são imutáveis var m := x; var n := y; r := 0; // Soma sucessiva para multiplicar dois números. while m > 0 { r := r + n; m := m - 1; } return r; // NOT(m>0) ^ Inv ==> r = x*y } /* Inv = m*n + r = x*y Mult(5,3) Teste de mesa x y m n r Inv --> m*n + r = x*y 5 3 5 3 0 5x3+0 = 5*3 5 3 4 3 3 4x3+3 = 5*3 5 3 3 3 6 3x3+6 = 5*3 5 3 2 3 9 2x3+9 = 5*3 5 3 1 3 12 1x3+12 = 5*3 5 3 0 3 15 0x3+15 = 5*3 */
231
FormalMethods_tmp_tmpvda2r3_o_dafny_Invariants_ex2.dfy
function Potencia(x:nat, y:nat):nat { if y == 0 then 1 else x * Potencia(x, y-1) } method Pot(x:nat, y:nat) returns (r:nat) ensures r == Potencia(x,y) { r := 1; var b := x; var e := y; while e > 0 invariant Potencia(b,e) * r == Potencia(x,y) { r := r * b; e := e - 1; } return r; } /* Inv = Pot(2,3) Teste de mesa x y b e r Inv --> b^e * r = x^y 2 3 2 3 1 2^3 * 2^0 = 2^3 2 3 2 2 1*2 2^2 * 2^1 = 2^3 2 3 2 1 1*2*2 2^1 * 2^2 = 2^3 2 3 2 0 1*2*2*2 2^0 * 2^3 = 2^3 */
function Potencia(x:nat, y:nat):nat { if y == 0 then 1 else x * Potencia(x, y-1) } method Pot(x:nat, y:nat) returns (r:nat) ensures r == Potencia(x,y) { r := 1; var b := x; var e := y; while e > 0 { r := r * b; e := e - 1; } return r; } /* Inv = Pot(2,3) Teste de mesa x y b e r Inv --> b^e * r = x^y 2 3 2 3 1 2^3 * 2^0 = 2^3 2 3 2 2 1*2 2^2 * 2^1 = 2^3 2 3 2 1 1*2*2 2^1 * 2^2 = 2^3 2 3 2 0 1*2*2*2 2^0 * 2^3 = 2^3 */
232
Formal_Verification_With_Dafny_tmp_tmp5j79rq48_Counter.dfy
class Counter { var value : int ; constructor init() ensures value == 0; { value := 0 ; } method getValue() returns (x:int) ensures x == value; { x := value ; } method inc() modifies this`value requires value >= 0; ensures value == old(value) + 1; { value := value + 1; } method dec() modifies this`value requires value > 0; ensures value == old(value) - 1; { value := value - 1 ; } method Main () { var count := new Counter.init() ; count.inc(); count.inc(); count.dec(); count.inc(); var aux : int := count.getValue(); assert (aux == 2) ; } }
class Counter { var value : int ; constructor init() ensures value == 0; { value := 0 ; } method getValue() returns (x:int) ensures x == value; { x := value ; } method inc() modifies this`value requires value >= 0; ensures value == old(value) + 1; { value := value + 1; } method dec() modifies this`value requires value > 0; ensures value == old(value) - 1; { value := value - 1 ; } method Main () { var count := new Counter.init() ; count.inc(); count.inc(); count.dec(); count.inc(); var aux : int := count.getValue(); } }
233
Formal_Verification_With_Dafny_tmp_tmp5j79rq48_LimitedStack.dfy
// A LIFO queue (aka a stack) with limited capacity. class LimitedStack{ var capacity : int; // capacity, max number of elements allowed on the stack. var arr : array<int>; // contents of stack. var top : int; // The index of the top of the stack, or -1 if the stack is empty // This predicate express a class invariant: All objects of this calls should satisfy this. predicate Valid() reads this; { arr != null && capacity > 0 && capacity == arr.Length && top >= -1 && top < capacity } predicate Empty() reads this`top; { top == -1 } predicate Full() reads this`top, this`capacity; { top == (capacity - 1) } method Init(c : int) modifies this; requires c > 0 ensures Valid() && Empty() && c == capacity ensures fresh(arr); // ensures arr is a newly created object. // Additional post-condition to be given here! { capacity := c; arr := new int[c]; top := -1; } method isEmpty() returns (res : bool) ensures res == Empty() { if(top == -1) { return true; } else { return false; } } // Returns the top element of the stack, without removing it. method Peek() returns (elem : int) requires Valid() && !Empty() ensures elem == arr[top] { return arr[top]; } // Pushed an element to the top of a (non full) stack. method Push(elem : int) modifies this`top, this.arr requires Valid() requires !Full() ensures Valid() && top == old(top) + 1 && arr[top] == elem ensures !old(Empty()) ==> forall i : int :: 0 <= i <= old(top) ==> arr[i] == old(arr[i]); { top := top + 1; arr[top] := elem; } // Pops the top element off the stack. method Pop() returns (elem : int) modifies this`top requires Valid() && !Empty() ensures Valid() && top == old(top) - 1 ensures elem == arr[old(top)] { elem := arr[top]; top := top - 1; return elem; } method Shift() requires Valid() && !Empty(); ensures Valid(); ensures forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); ensures top == old(top) - 1; modifies this.arr, this`top; { var i : int := 0; while (i < capacity - 1 ) invariant 0 <= i < capacity; invariant top == old(top); invariant forall j : int :: 0 <= j < i ==> arr[j] == old(arr[j + 1]); invariant forall j : int :: i <= j < capacity ==> arr[j] == old(arr[j]); { arr[i] := arr[i + 1]; i := i + 1; } top := top - 1; } //Push onto full stack, oldest element is discarded. method Push2(elem : int) modifies this.arr, this`top requires Valid() ensures Valid() && !Empty() ensures arr[top] == elem ensures old(!Full()) ==> top == old(top) + 1 && old(Full()) ==> top == old(top) ensures ((old(Full()) ==> arr[capacity - 1] == elem) && (old(!Full()) ==> (top == old(top) + 1 && arr[top] == elem) )) ensures old(Full()) ==> forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); { if(top == capacity - 1){ Shift(); top := top + 1; arr[top] := elem; } else{ top := top + 1; arr[top] := elem; } } // When you are finished, all the below assertions should be provable. // Feel free to add extra ones as well. method Main(){ var s := new LimitedStack; s.Init(3); assert s.Empty() && !s.Full(); s.Push(27); assert !s.Empty(); var e := s.Pop(); assert e == 27; assert s.top == -1; assert s.Empty() && !s.Full(); s.Push(5); assert s.top == 0; assert s.capacity == 3; s.Push(32); s.Push(9); assert s.Full(); assert s.arr[0] == 5; var e2 := s.Pop(); assert e2 == 9 && !s.Full(); assert s.arr[0] == 5; s.Push(e2); s.Push2(99); var e3 := s.Peek(); assert e3 == 99; assert s.arr[0] == 32; } }
// A LIFO queue (aka a stack) with limited capacity. class LimitedStack{ var capacity : int; // capacity, max number of elements allowed on the stack. var arr : array<int>; // contents of stack. var top : int; // The index of the top of the stack, or -1 if the stack is empty // This predicate express a class invariant: All objects of this calls should satisfy this. predicate Valid() reads this; { arr != null && capacity > 0 && capacity == arr.Length && top >= -1 && top < capacity } predicate Empty() reads this`top; { top == -1 } predicate Full() reads this`top, this`capacity; { top == (capacity - 1) } method Init(c : int) modifies this; requires c > 0 ensures Valid() && Empty() && c == capacity ensures fresh(arr); // ensures arr is a newly created object. // Additional post-condition to be given here! { capacity := c; arr := new int[c]; top := -1; } method isEmpty() returns (res : bool) ensures res == Empty() { if(top == -1) { return true; } else { return false; } } // Returns the top element of the stack, without removing it. method Peek() returns (elem : int) requires Valid() && !Empty() ensures elem == arr[top] { return arr[top]; } // Pushed an element to the top of a (non full) stack. method Push(elem : int) modifies this`top, this.arr requires Valid() requires !Full() ensures Valid() && top == old(top) + 1 && arr[top] == elem ensures !old(Empty()) ==> forall i : int :: 0 <= i <= old(top) ==> arr[i] == old(arr[i]); { top := top + 1; arr[top] := elem; } // Pops the top element off the stack. method Pop() returns (elem : int) modifies this`top requires Valid() && !Empty() ensures Valid() && top == old(top) - 1 ensures elem == arr[old(top)] { elem := arr[top]; top := top - 1; return elem; } method Shift() requires Valid() && !Empty(); ensures Valid(); ensures forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); ensures top == old(top) - 1; modifies this.arr, this`top; { var i : int := 0; while (i < capacity - 1 ) { arr[i] := arr[i + 1]; i := i + 1; } top := top - 1; } //Push onto full stack, oldest element is discarded. method Push2(elem : int) modifies this.arr, this`top requires Valid() ensures Valid() && !Empty() ensures arr[top] == elem ensures old(!Full()) ==> top == old(top) + 1 && old(Full()) ==> top == old(top) ensures ((old(Full()) ==> arr[capacity - 1] == elem) && (old(!Full()) ==> (top == old(top) + 1 && arr[top] == elem) )) ensures old(Full()) ==> forall i : int :: 0 <= i < capacity - 1 ==> arr[i] == old(arr[i + 1]); { if(top == capacity - 1){ Shift(); top := top + 1; arr[top] := elem; } else{ top := top + 1; arr[top] := elem; } } // When you are finished, all the below assertions should be provable. // Feel free to add extra ones as well. method Main(){ var s := new LimitedStack; s.Init(3); s.Push(27); var e := s.Pop(); s.Push(5); s.Push(32); s.Push(9); var e2 := s.Pop(); s.Push(e2); s.Push2(99); var e3 := s.Peek(); } }
234
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Binary Search_binary_search.dfy
// Dafny verification of binary search alogirthm from binary_search.py // Inspired by: https://ece.uwaterloo.ca/~agurfink/stqam/rise4fun-Dafny/#h211 method BinarySearch(arr: array<int>, target: int) returns (index: int) requires distinct(arr) requires sorted(arr) ensures -1 <= index < arr.Length ensures index == -1 ==> not_found(arr, target) ensures index != -1 ==> found(arr, target, index) { var low, high := 0 , arr.Length-1; while low <= high invariant 0 <= low <= high + 1 invariant low-1 <= high < arr.Length invariant forall i :: 0 <= i <= low && high <= i < arr.Length ==> arr[i] != target { var mid := (low + high) / 2; if arr[mid] == target { return mid; } else if arr[mid] < target { low := mid + 1; } else { high := mid - 1; } } return -1; } // Predicate to check that the array is sorted predicate sorted(a: array<int>) reads a { forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] } // Predicate to that each element is unique predicate distinct(arr: array<int>) reads arr { forall i, j :: 0 <= i < arr.Length && 0 <= j < arr.Length ==> arr[i] != arr[j] } // Predicate to that the target is not in the array predicate not_found(arr: array<int>, target: int) reads arr { (forall j :: 0 <= j < arr.Length ==> arr[j] != target) } // Predicate to that the target is in the array predicate found(arr: array<int>, target: int, index: int) requires -1 <= index < arr.Length; reads arr { if index == -1 then false else if arr[index] == target then true else false }
// Dafny verification of binary search alogirthm from binary_search.py // Inspired by: https://ece.uwaterloo.ca/~agurfink/stqam/rise4fun-Dafny/#h211 method BinarySearch(arr: array<int>, target: int) returns (index: int) requires distinct(arr) requires sorted(arr) ensures -1 <= index < arr.Length ensures index == -1 ==> not_found(arr, target) ensures index != -1 ==> found(arr, target, index) { var low, high := 0 , arr.Length-1; while low <= high { var mid := (low + high) / 2; if arr[mid] == target { return mid; } else if arr[mid] < target { low := mid + 1; } else { high := mid - 1; } } return -1; } // Predicate to check that the array is sorted predicate sorted(a: array<int>) reads a { forall j, k :: 0 <= j < k < a.Length ==> a[j] <= a[k] } // Predicate to that each element is unique predicate distinct(arr: array<int>) reads arr { forall i, j :: 0 <= i < arr.Length && 0 <= j < arr.Length ==> arr[i] != arr[j] } // Predicate to that the target is not in the array predicate not_found(arr: array<int>, target: int) reads arr { (forall j :: 0 <= j < arr.Length ==> arr[j] != target) } // Predicate to that the target is in the array predicate found(arr: array<int>, target: int, index: int) requires -1 <= index < arr.Length; reads arr { if index == -1 then false else if arr[index] == target then true else false }
235
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Largest Sum_largest_sum.dfy
// CoPilot function converted to dafny method largest_sum(nums: array<int>, k: int) returns (sum: int) requires nums.Length > 0 ensures max_sum_subarray(nums, sum, 0, nums.Length) { var max_sum := 0; var current_sum := 0; var i := 0; while (i < nums.Length) invariant 0 <= i <= nums.Length invariant max_sum_subarray(nums, max_sum, 0, i) // Invariant for the max_sum invariant forall j :: 0 <= j < i ==> Sum_Array(nums, j, i) <= current_sum // Invariant for the current_sum { current_sum := current_sum + nums[i]; if (current_sum > max_sum) { max_sum := current_sum; } if (current_sum < 0) { current_sum := 0; } i := i + 1; } return max_sum; } // Predicate to confirm that sum is the maximum summation of element [start, stop) predicate max_sum_subarray(arr: array<int>, sum: int, start: int, stop: int) requires arr.Length > 0 requires 0 <= start <= stop <= arr.Length reads arr { forall u, v :: start <= u < v <= stop ==> Sum_Array(arr, u, v) <= sum } //Sums array elements between [start, stop) function Sum_Array(arr: array<int>, start: int, stop: int): int requires 0 <= start <= stop <= arr.Length decreases stop - start reads arr { if start >= stop then 0 else arr[stop-1] + Sum_Array(arr, start, stop-1) }
// CoPilot function converted to dafny method largest_sum(nums: array<int>, k: int) returns (sum: int) requires nums.Length > 0 ensures max_sum_subarray(nums, sum, 0, nums.Length) { var max_sum := 0; var current_sum := 0; var i := 0; while (i < nums.Length) { current_sum := current_sum + nums[i]; if (current_sum > max_sum) { max_sum := current_sum; } if (current_sum < 0) { current_sum := 0; } i := i + 1; } return max_sum; } // Predicate to confirm that sum is the maximum summation of element [start, stop) predicate max_sum_subarray(arr: array<int>, sum: int, start: int, stop: int) requires arr.Length > 0 requires 0 <= start <= stop <= arr.Length reads arr { forall u, v :: start <= u < v <= stop ==> Sum_Array(arr, u, v) <= sum } //Sums array elements between [start, stop) function Sum_Array(arr: array<int>, start: int, stop: int): int requires 0 <= start <= stop <= arr.Length reads arr { if start >= stop then 0 else arr[stop-1] + Sum_Array(arr, start, stop-1) }
236
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Sort Array_sort_array.dfy
method sortArray(arr: array<int>) returns (arr_sorted: array<int>) // Requires array length to be between 0 and 10000 requires 0 <= arr.Length < 10000 // Ensuring the arry has been sorted ensures sorted(arr_sorted, 0, arr_sorted.Length) // Ensuring that we have not modified elements but have only changed their indices ensures multiset(arr[..]) == multiset(arr_sorted[..]) // Modifies arr modifies arr { var i := 0; while i < arr.Length invariant i <= arr.Length invariant sorted(arr, 0, i) invariant multiset(old(arr[..])) == multiset(arr[..]) invariant forall u, v :: 0 <= u < i && i <= v < arr.Length ==> arr[u] <= arr[v] invariant pivot(arr, i) { var j := i; while j < arr.Length invariant j <= arr.Length invariant multiset(old(arr[..])) == multiset(arr[..]) invariant pivot(arr, i) invariant forall u :: i < u < j ==> arr[i] <= arr[u] invariant forall u :: 0 <= u < i ==> arr[u] <= arr[i] invariant sorted(arr, 0, i+1) { if arr[i] > arr[j] { var temp := arr[i]; arr[i] := arr[j]; arr[j] := temp; } j := j + 1; } i := i + 1; } return arr; } // Predicate to determine whether the list is sorted between [start, stop) predicate sorted(arr: array<int>, start: int, end: int) requires 0 <= start <= end <= arr.Length reads arr { forall i, j :: start <= i <= j < end ==> arr[i] <= arr[j] } // Predicate to determine whether element arr[pivot] is a pivot point // Based on: https://github.com/stqam/dafny/blob/master/BubbleSort.dfy predicate pivot(arr: array<int>, pivot: int) requires 0 <= pivot <= arr.Length reads arr { forall u, v :: 0 <= u < pivot < v < arr.Length ==> arr[u] <= arr[v] }
method sortArray(arr: array<int>) returns (arr_sorted: array<int>) // Requires array length to be between 0 and 10000 requires 0 <= arr.Length < 10000 // Ensuring the arry has been sorted ensures sorted(arr_sorted, 0, arr_sorted.Length) // Ensuring that we have not modified elements but have only changed their indices ensures multiset(arr[..]) == multiset(arr_sorted[..]) // Modifies arr modifies arr { var i := 0; while i < arr.Length { var j := i; while j < arr.Length { if arr[i] > arr[j] { var temp := arr[i]; arr[i] := arr[j]; arr[j] := temp; } j := j + 1; } i := i + 1; } return arr; } // Predicate to determine whether the list is sorted between [start, stop) predicate sorted(arr: array<int>, start: int, end: int) requires 0 <= start <= end <= arr.Length reads arr { forall i, j :: start <= i <= j < end ==> arr[i] <= arr[j] } // Predicate to determine whether element arr[pivot] is a pivot point // Based on: https://github.com/stqam/dafny/blob/master/BubbleSort.dfy predicate pivot(arr: array<int>, pivot: int) requires 0 <= pivot <= arr.Length reads arr { forall u, v :: 0 <= u < pivot < v < arr.Length ==> arr[u] <= arr[v] }
237
HATRA-2022-Paper_tmp_tmp5texxy8l_copilot_verification_Two Sum_two_sum.dfy
method twoSum(nums: array<int>, target: int) returns (index1: int, index2: int) requires 2 <= nums.Length requires exists i, j :: (0 <= i < j < nums.Length && nums[i] + nums[j] == target) ensures index1 != index2 ensures 0 <= index1 < nums.Length ensures 0 <= index2 < nums.Length ensures nums[index1] + nums[index2] == target { var i := 0; while i < nums.Length invariant 0 <= i < nums.Length invariant forall u, v :: 0 <= u < v < nums.Length && u < i ==> nums[u] + nums[v] != target invariant exists u, v :: i <= u < v < nums.Length && nums[u] + nums[v] == target { var j := i + 1; while j < nums.Length invariant 0 <= i < j <= nums.Length invariant forall u, v :: 0 <= u < v < nums.Length && u < i ==> nums[u] + nums[v] != target invariant exists u, v :: i <= u < v < nums.Length && nums[u] + nums[v] == target invariant forall u :: i < u < j ==> nums[i] + nums[u] != target { if nums[i] + nums[j] == target { return i, j; } j := j + 1; } i := i + 1; } }
method twoSum(nums: array<int>, target: int) returns (index1: int, index2: int) requires 2 <= nums.Length requires exists i, j :: (0 <= i < j < nums.Length && nums[i] + nums[j] == target) ensures index1 != index2 ensures 0 <= index1 < nums.Length ensures 0 <= index2 < nums.Length ensures nums[index1] + nums[index2] == target { var i := 0; while i < nums.Length { var j := i + 1; while j < nums.Length { if nums[i] + nums[j] == target { return i, j; } j := j + 1; } i := i + 1; } }
238
Invoker_tmp_tmpypx0gs8x_dafny_abstract-interpreter_SimpleVerifier.dfy
module Ints { const U32_BOUND: nat := 0x1_0000_0000 newtype u32 = x:int | 0 <= x < 0x1_0000_0000 newtype i32 = x: int | -0x8000_0000 <= x < 0x8000_0000 } module Lang { import opened Ints datatype Reg = R0 | R1 | R2 | R3 datatype Expr = | Const(n: u32) // overflow during addition is an error | Add(r1: Reg, r2: Reg) // this is saturating subtraction (to allow comparing numbers) | Sub(r1: Reg, r2: Reg) datatype Stmt = | Assign(r: Reg, e: Expr) // Jump by offset if condition is true | JmpZero(r: Reg, offset: i32) datatype Program = Program(stmts: seq<Stmt>) } /* Well-formed check: offsets are all within the program */ /* Main safety property: additions do not overflow */ /* First, we give the concrete semantics of programs. */ module ConcreteEval { import opened Ints import opened Lang type State = Reg -> u32 function update_state(s: State, r0: Reg, v: u32): State { ((r: Reg) => if r == r0 then v else s(r)) } datatype Option<T> = Some(v: T) | None function expr_eval(env: State, e: Expr): Option<u32> { match e { case Const(n) => Some(n) case Add(r1, r2) => (if (env(r1) as int + env(r2) as int >= U32_BOUND) then None else Some(env(r1) + env(r2))) case Sub(r1, r2) => (if env(r1) as int - env(r2) as int < 0 then Some(0) else Some(env(r1) - env(r2))) } } // stmt_step executes a single statement // // Returns a new state and a relative PC offset (which is 1 for non-jump // statements). function stmt_step(env: State, s: Stmt): Option<(State, int)> { match s { case Assign(r, e) => var e' := expr_eval(env, e); match e' { case Some(v) => Some((update_state(env, r, v), 1)) case None => None } case JmpZero(r, offset) => Some((env, (if env(r) == 0 then offset else 1) as int)) } } datatype ExecResult = Ok(env: State) | NoFuel | Error // Run a program starting at pc. // // The sequence of statements is constant, meant to reflect a static program. // Termination occurs if the pc ever reaches exactly the end. // // Errors can come from either executing statements (see stmt_step for those // errors), or from an out-of-bounds pc (negative or not past the end of ss). // // fuel is needed to make this function terminate; the idea is that if there // exists some fuel that makes the program terminate, that is it's complete // execution, and if it always runs out of fuel it has an infinite loop. function stmts_step(env: State, ss: seq<Stmt>, pc: nat, fuel: nat): ExecResult requires pc <= |ss| decreases fuel { if fuel == 0 then NoFuel else if pc == |ss| then Ok(env) else match stmt_step(env, ss[pc]) { case None => Error case Some((env', offset)) => if !(0 <= pc + offset <= |ss|) then Error else stmts_step(env', ss, pc + offset, fuel - 1) } } } /* Now we turn to analyzing programs */ module AbstractEval { import opened Ints import opened Lang datatype Val = Interval(lo: int, hi: int) datatype AbstractState = AbstractState(rs: Reg -> Val) function expr_eval(env: AbstractState, e: Expr): Val { match e { case Const(n) => Interval(n as int, n as int) case Add(r1, r2) => var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(v1.lo + v2.lo, v1.hi + v2.hi) case Sub(r1, r2) => // this was quite buggy initially: low is bounded (due to saturating // subtraction), and upper bound also should cannot go negative var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(0, if v1.hi - v2.lo >= 0 then v1.hi - v2.lo else 0) } } function update_state(env: AbstractState, r0: Reg, v: Val): AbstractState { AbstractState((r: Reg) => if r == r0 then v else env.rs(r)) } // function stmt_step(env: State, s: Stmt): Option<(State, int)> function stmt_eval(env: AbstractState, s: Stmt): (AbstractState, set<int>) { match s { case Assign(r, e) => var v := expr_eval(env, e); (update_state(env, r, v), {1 as int}) case JmpZero(r, offset) => // imprecise analysis: we don't try to prove that this jump is or isn't taken (env, {offset as int, 1}) } } /* TODO(tej): to interpret a program, we need to explore all paths. Along the * way, we would have to look for loops - our plan is to disallow them (unlike * a normal abstract interpretation which would try to run till a fixpoint). */ // Implement a check for just the jump targets, which are static and thus // don't even need abstract interpretation. // Check that jump targets ss[from..] are valid. function has_valid_jump_targets(ss: seq<Stmt>, from: nat): bool decreases |ss|-from requires from <= |ss| { if from == |ss| then true else (match ss[from] { case JmpZero(_, offset) => 0 <= from + offset as int <= |ss| case _ => true } && has_valid_jump_targets(ss, from+1)) } ghost predicate valid_jump_targets(ss: seq<Stmt>) { forall i | 0 <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss| } lemma has_valid_jump_targets_ok_helper(ss: seq<Stmt>, from: nat) requires from <= |ss| decreases |ss|-from ensures has_valid_jump_targets(ss, from) <==> (forall i | from <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|) { } lemma has_valid_jump_targets_ok(ss: seq<Stmt>) ensures has_valid_jump_targets(ss, 0) <==> valid_jump_targets(ss) { has_valid_jump_targets_ok_helper(ss, 0); } } module AbstractEvalProof { import opened Ints import opened Lang import E = ConcreteEval import opened AbstractEval /* What does it mean for a concrete state to be captured by an abstract state? * (Alternately, interpret each abstract state as a set of concrete states) */ ghost predicate reg_included(c_v: u32, v: Val) { v.lo <= c_v as int <= v.hi } ghost predicate state_included(env: E.State, abs: AbstractState) { forall r: Reg :: reg_included(env(r), abs.rs(r)) } lemma expr_eval_ok(env: E.State, abs: AbstractState, e: Expr) requires state_included(env, abs) requires E.expr_eval(env, e).Some? ensures reg_included(E.expr_eval(env, e).v, expr_eval(abs, e)) { match e { case Add(_, _) => { return; } case Const(_) => { return; } case Sub(r1, r2) => { /* debugging bug in the abstract interpretation */ assert reg_included(env(r1), abs.rs(r1)); assert reg_included(env(r2), abs.rs(r2)); assert env(r1) as int <= abs.rs(r1).hi; assert env(r2) as int >= abs.rs(r2).lo; if env(r1) <= env(r2) { assert E.expr_eval(env, e).v == 0; return; } assert E.expr_eval(env, e).v as int == env(r1) as int - env(r2) as int; return; } } } lemma stmt_eval_ok(env: E.State, abs: AbstractState, stmt: Stmt) requires state_included(env, abs) requires E.stmt_step(env, stmt).Some? ensures state_included(E.stmt_step(env, stmt).v.0, stmt_eval(abs, stmt).0) {} }
module Ints { const U32_BOUND: nat := 0x1_0000_0000 newtype u32 = x:int | 0 <= x < 0x1_0000_0000 newtype i32 = x: int | -0x8000_0000 <= x < 0x8000_0000 } module Lang { import opened Ints datatype Reg = R0 | R1 | R2 | R3 datatype Expr = | Const(n: u32) // overflow during addition is an error | Add(r1: Reg, r2: Reg) // this is saturating subtraction (to allow comparing numbers) | Sub(r1: Reg, r2: Reg) datatype Stmt = | Assign(r: Reg, e: Expr) // Jump by offset if condition is true | JmpZero(r: Reg, offset: i32) datatype Program = Program(stmts: seq<Stmt>) } /* Well-formed check: offsets are all within the program */ /* Main safety property: additions do not overflow */ /* First, we give the concrete semantics of programs. */ module ConcreteEval { import opened Ints import opened Lang type State = Reg -> u32 function update_state(s: State, r0: Reg, v: u32): State { ((r: Reg) => if r == r0 then v else s(r)) } datatype Option<T> = Some(v: T) | None function expr_eval(env: State, e: Expr): Option<u32> { match e { case Const(n) => Some(n) case Add(r1, r2) => (if (env(r1) as int + env(r2) as int >= U32_BOUND) then None else Some(env(r1) + env(r2))) case Sub(r1, r2) => (if env(r1) as int - env(r2) as int < 0 then Some(0) else Some(env(r1) - env(r2))) } } // stmt_step executes a single statement // // Returns a new state and a relative PC offset (which is 1 for non-jump // statements). function stmt_step(env: State, s: Stmt): Option<(State, int)> { match s { case Assign(r, e) => var e' := expr_eval(env, e); match e' { case Some(v) => Some((update_state(env, r, v), 1)) case None => None } case JmpZero(r, offset) => Some((env, (if env(r) == 0 then offset else 1) as int)) } } datatype ExecResult = Ok(env: State) | NoFuel | Error // Run a program starting at pc. // // The sequence of statements is constant, meant to reflect a static program. // Termination occurs if the pc ever reaches exactly the end. // // Errors can come from either executing statements (see stmt_step for those // errors), or from an out-of-bounds pc (negative or not past the end of ss). // // fuel is needed to make this function terminate; the idea is that if there // exists some fuel that makes the program terminate, that is it's complete // execution, and if it always runs out of fuel it has an infinite loop. function stmts_step(env: State, ss: seq<Stmt>, pc: nat, fuel: nat): ExecResult requires pc <= |ss| { if fuel == 0 then NoFuel else if pc == |ss| then Ok(env) else match stmt_step(env, ss[pc]) { case None => Error case Some((env', offset)) => if !(0 <= pc + offset <= |ss|) then Error else stmts_step(env', ss, pc + offset, fuel - 1) } } } /* Now we turn to analyzing programs */ module AbstractEval { import opened Ints import opened Lang datatype Val = Interval(lo: int, hi: int) datatype AbstractState = AbstractState(rs: Reg -> Val) function expr_eval(env: AbstractState, e: Expr): Val { match e { case Const(n) => Interval(n as int, n as int) case Add(r1, r2) => var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(v1.lo + v2.lo, v1.hi + v2.hi) case Sub(r1, r2) => // this was quite buggy initially: low is bounded (due to saturating // subtraction), and upper bound also should cannot go negative var v1 := env.rs(r1); var v2 := env.rs(r2); Interval(0, if v1.hi - v2.lo >= 0 then v1.hi - v2.lo else 0) } } function update_state(env: AbstractState, r0: Reg, v: Val): AbstractState { AbstractState((r: Reg) => if r == r0 then v else env.rs(r)) } // function stmt_step(env: State, s: Stmt): Option<(State, int)> function stmt_eval(env: AbstractState, s: Stmt): (AbstractState, set<int>) { match s { case Assign(r, e) => var v := expr_eval(env, e); (update_state(env, r, v), {1 as int}) case JmpZero(r, offset) => // imprecise analysis: we don't try to prove that this jump is or isn't taken (env, {offset as int, 1}) } } /* TODO(tej): to interpret a program, we need to explore all paths. Along the * way, we would have to look for loops - our plan is to disallow them (unlike * a normal abstract interpretation which would try to run till a fixpoint). */ // Implement a check for just the jump targets, which are static and thus // don't even need abstract interpretation. // Check that jump targets ss[from..] are valid. function has_valid_jump_targets(ss: seq<Stmt>, from: nat): bool requires from <= |ss| { if from == |ss| then true else (match ss[from] { case JmpZero(_, offset) => 0 <= from + offset as int <= |ss| case _ => true } && has_valid_jump_targets(ss, from+1)) } ghost predicate valid_jump_targets(ss: seq<Stmt>) { forall i | 0 <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss| } lemma has_valid_jump_targets_ok_helper(ss: seq<Stmt>, from: nat) requires from <= |ss| ensures has_valid_jump_targets(ss, from) <==> (forall i | from <= i < |ss| :: ss[i].JmpZero? ==> 0 <= i + ss[i].offset as int <= |ss|) { } lemma has_valid_jump_targets_ok(ss: seq<Stmt>) ensures has_valid_jump_targets(ss, 0) <==> valid_jump_targets(ss) { has_valid_jump_targets_ok_helper(ss, 0); } } module AbstractEvalProof { import opened Ints import opened Lang import E = ConcreteEval import opened AbstractEval /* What does it mean for a concrete state to be captured by an abstract state? * (Alternately, interpret each abstract state as a set of concrete states) */ ghost predicate reg_included(c_v: u32, v: Val) { v.lo <= c_v as int <= v.hi } ghost predicate state_included(env: E.State, abs: AbstractState) { forall r: Reg :: reg_included(env(r), abs.rs(r)) } lemma expr_eval_ok(env: E.State, abs: AbstractState, e: Expr) requires state_included(env, abs) requires E.expr_eval(env, e).Some? ensures reg_included(E.expr_eval(env, e).v, expr_eval(abs, e)) { match e { case Add(_, _) => { return; } case Const(_) => { return; } case Sub(r1, r2) => { /* debugging bug in the abstract interpretation */ if env(r1) <= env(r2) { return; } return; } } } lemma stmt_eval_ok(env: E.State, abs: AbstractState, stmt: Stmt) requires state_included(env, abs) requires E.stmt_step(env, stmt).Some? ensures state_included(E.stmt_step(env, stmt).v.0, stmt_eval(abs, stmt).0) {} }
239
M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo4-CountAndReturn.dfy
method CountToAndReturnN(n: int) returns (r: int) requires n >= 0 ensures r == n { var i := 0; while i < n invariant 0 <= i <= n { i := i + 1; } r := i; }
method CountToAndReturnN(n: int) returns (r: int) requires n >= 0 ensures r == n { var i := 0; while i < n { i := i + 1; } r := i; }
240
M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo7-ComputeSum.dfy
function Sum(n:nat):nat { if n==0 then 0 else n + Sum(n-1) } method ComputeSum(n:nat) returns (s:nat) ensures s ==Sum(n) { s := 0; var i := 0; while i< n invariant 0 <= i <= n invariant s == Sum(i) { s := s + i + 1; i := i+1; } }
function Sum(n:nat):nat { if n==0 then 0 else n + Sum(n-1) } method ComputeSum(n:nat) returns (s:nat) ensures s ==Sum(n) { s := 0; var i := 0; while i< n { s := s + i + 1; i := i+1; } }
241
M2_tmp_tmp2laaavvl_Software Verification_Exercices_Exo9-Carre.dfy
method Carre(a: nat) returns (c: nat) ensures c == a*a { var i := 0; c := 0; while i != a invariant 0 <= i <= a invariant c == i*i decreases a - i { c := c + 2*i +1; i := i + 1; } }
method Carre(a: nat) returns (c: nat) ensures c == a*a { var i := 0; c := 0; while i != a { c := c + 2*i +1; i := i + 1; } }
242
MFDS_tmp_tmpvvr5y1t9_Assignments_Ass-1-2020-21-Sol-eGela.dfy
// Ejercicio 1: Demostrar por inducci�n el siguiente lema: lemma EcCuadDiv2_Lemma (x:int) requires x >= 1 ensures (x*x + x) % 2 == 0 { if x != 1 { EcCuadDiv2_Lemma(x-1); assert x*x+x == ((x-1)*(x-1) + (x-1)) + 2*x; } } // Ejercicio 2: Demostrar por inducci�n el siguiente lema // Indicaciones: (1) Puedes llamar al lema del ejercicio anterior, si lo necesitas. // (2) Recuerda que, a veces, simplificar la HI puede ayudar a saber donde utilizarla. lemma EcCubicaDiv6_Lemma (x:int) requires x >= 1 ensures (x*x*x + 3*x*x + 2*x) % 6 == 0 { if x>1 { EcCubicaDiv6_Lemma(x-1); //assert ((x-1)*(x-1)*(x-1) + 3*(x-1)*(x-1) + 2*(x-1)) % 6 == 0; //HI assert (x*x*x - 3*x*x + 3*x -1 + 3*x*x - 6*x + 3 + 2*x -2) % 6 == 0; //HI assert (x*x*x - x) % 6 == 0; //HI assert x*x*x + 3*x*x + 2*x == (x*x*x - x) + 3*(x*x + x); EcCuadDiv2_Lemma(x); } } // Ejercicio 3: Probar por contradicci�n el siguiente lemma: lemma cubEven_Lemma (x:int) requires (x*x*x + 5) % 2 == 1 ensures x % 2 == 0 { if x%2 == 1 { var k := (x-1)/2; assert x*x*x + 5 == (2*k+1)*(2*k+1)*(2*k+1) + 5 == 8*k*k*k + 12*k*k + 6*k + 6 == 2*(4*k*k*k + 6*k*k + 3*k + 3); assert false; } } // Ejercicio 4: Prueba el siguiente lemma por casos (de acuerdo a los tres valores posibles de x%3) lemma perfectCube_Lemma (x:int) ensures exists z :: (x*x*x == 3*z || x*x*x == 3*z + 1 || x*x*x == 3*z - 1); { if x%3 == 0 { var k := x/3; assert x*x*x == 27*k*k*k == 3*(9*k*k*k); } else if x%3 == 1 { var k := (x-1)/3; assert x*x*x == (3*k+1)*(3*k+1)*(3*k+1) == 27*k*k*k + 27*k*k + 9*k + 1; assert x*x*x == 3*(9*k*k*k + 9*k*k + 3*k) + 1; } else { var k := (x-2)/3; assert x*x*x == (3*k+2)*(3*k+2)*(3*k+2) == 27*k*k*k + 54*k*k + 36*k + 8; assert x*x*x == 3*(9*k*k*k + 18*k*k + 12*k + 3) - 1; } } // Ejercicio 5: Dada la siguiente funci�n exp y los dos lemmas expGET1_Lemma y prodMon_Lemma (que Dafny demuestra autom�ticamente) // demostrar el lemma expMon_Lemma por inducci�n en n. Usar calc {} y poner como "hints" las llamadas a los lemmas en los // pasos del c�lculo donde son utilizadas. function exp(x:int, e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma expGET1_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} lemma prodMon_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} lemma expMon_Lemma(x:int, n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n != 1 { calc { exp(x+1,n); == (x+1)*exp(x+1,n-1); == x*exp(x+1,n-1) + exp(x+1,n-1); >= { expGET1_Lemma(x+1,n-1); } x*exp(x+1,n-1); >= { expMon_Lemma(x,n-1); //assert exp(x+1,n-1) >= (exp(x,n-1) + 1); expGET1_Lemma(x+1,n-1); //assert exp(x+1,n-1) >= 1; expGET1_Lemma(x,n-1); //assert (exp(x,n-1) + 1) >= 1; prodMon_Lemma(x, exp(x+1,n-1), exp(x,n-1) + 1); //assert x*exp(x+1,n-1) >= x*(exp(x,n-1) + 1); } x*(exp(x,n-1) + 1); == x*exp(x,n-1) + x; >= exp(x,n)+1; } } }
// Ejercicio 1: Demostrar por inducci�n el siguiente lema: lemma EcCuadDiv2_Lemma (x:int) requires x >= 1 ensures (x*x + x) % 2 == 0 { if x != 1 { EcCuadDiv2_Lemma(x-1); } } // Ejercicio 2: Demostrar por inducci�n el siguiente lema // Indicaciones: (1) Puedes llamar al lema del ejercicio anterior, si lo necesitas. // (2) Recuerda que, a veces, simplificar la HI puede ayudar a saber donde utilizarla. lemma EcCubicaDiv6_Lemma (x:int) requires x >= 1 ensures (x*x*x + 3*x*x + 2*x) % 6 == 0 { if x>1 { EcCubicaDiv6_Lemma(x-1); //assert ((x-1)*(x-1)*(x-1) + 3*(x-1)*(x-1) + 2*(x-1)) % 6 == 0; //HI EcCuadDiv2_Lemma(x); } } // Ejercicio 3: Probar por contradicci�n el siguiente lemma: lemma cubEven_Lemma (x:int) requires (x*x*x + 5) % 2 == 1 ensures x % 2 == 0 { if x%2 == 1 { var k := (x-1)/2; == 8*k*k*k + 12*k*k + 6*k + 6 == 2*(4*k*k*k + 6*k*k + 3*k + 3); } } // Ejercicio 4: Prueba el siguiente lemma por casos (de acuerdo a los tres valores posibles de x%3) lemma perfectCube_Lemma (x:int) ensures exists z :: (x*x*x == 3*z || x*x*x == 3*z + 1 || x*x*x == 3*z - 1); { if x%3 == 0 { var k := x/3; } else if x%3 == 1 { var k := (x-1)/3; } else { var k := (x-2)/3; } } // Ejercicio 5: Dada la siguiente funci�n exp y los dos lemmas expGET1_Lemma y prodMon_Lemma (que Dafny demuestra autom�ticamente) // demostrar el lemma expMon_Lemma por inducci�n en n. Usar calc {} y poner como "hints" las llamadas a los lemmas en los // pasos del c�lculo donde son utilizadas. function exp(x:int, e:nat):int { if e == 0 then 1 else x * exp(x,e-1) } lemma expGET1_Lemma(x:int, e:nat) requires x >= 1 ensures exp(x,e) >= 1 {} lemma prodMon_Lemma(z:int, a:int, b:int) requires z >= 1 && a >= b >= 1 ensures z*a >= z*b {} lemma expMon_Lemma(x:int, n:nat) requires x >= 1 && n >= 1 ensures exp(x+1,n) >= exp(x,n) + 1 { if n != 1 { calc { exp(x+1,n); == (x+1)*exp(x+1,n-1); == x*exp(x+1,n-1) + exp(x+1,n-1); >= { expGET1_Lemma(x+1,n-1); } x*exp(x+1,n-1); >= { expMon_Lemma(x,n-1); //assert exp(x+1,n-1) >= (exp(x,n-1) + 1); expGET1_Lemma(x+1,n-1); //assert exp(x+1,n-1) >= 1; expGET1_Lemma(x,n-1); //assert (exp(x,n-1) + 1) >= 1; prodMon_Lemma(x, exp(x+1,n-1), exp(x,n-1) + 1); //assert x*exp(x+1,n-1) >= x*(exp(x,n-1) + 1); } x*(exp(x,n-1) + 1); == x*exp(x,n-1) + x; >= exp(x,n)+1; } } }
243
MFES_2021_tmp_tmpuljn8zd9_Exams_Special_Exam_03_2020_4_CatalanNumbers.dfy
function C(n: nat): nat decreases n { if n == 0 then 1 else (4 * n - 2) * C(n-1) / (n + 1) } method calcC(n: nat) returns (res: nat) ensures res == C(n) { var i := 0; res := 1; assert res == C(i) && 0 <= i <= n; while i < n decreases n - i //a - loop variant invariant res == C(i) && 0 <= i <= n //b - loop invariant { ghost var v0 := n - i; assert res == C(i) && 0 <= i <= n && i < n && n - i == v0; i := i + 1; res := (4 * i - 2) * res / (i + 1); assert res == C(i) && 0 <= i <= n && 0 <= n - i < v0; } assert res == C(i) && 0 <= i <= n && i >= n; }
function C(n: nat): nat { if n == 0 then 1 else (4 * n - 2) * C(n-1) / (n + 1) } method calcC(n: nat) returns (res: nat) ensures res == C(n) { var i := 0; res := 1; while i < n { ghost var v0 := n - i; i := i + 1; res := (4 * i - 2) * res / (i + 1); } }
244
MFES_2021_tmp_tmpuljn8zd9_FCUL_Exercises_10_find.dfy
method find(a: array<int>, key: int) returns(index: int) requires a.Length > 0; ensures 0 <= index <= a.Length; ensures index < a.Length ==> a[index] == key; { index := 0; while index < a.Length && a[index] != key decreases a.Length - index invariant 0 <= index <= a.Length invariant forall x :: 0 <= x < index ==> a[x] != key { index := index + 1; } }
method find(a: array<int>, key: int) returns(index: int) requires a.Length > 0; ensures 0 <= index <= a.Length; ensures index < a.Length ==> a[index] == key; { index := 0; while index < a.Length && a[index] != key { index := index + 1; } }
245
MFES_2021_tmp_tmpuljn8zd9_FCUL_Exercises_8_sum.dfy
function calcSum(n: nat) : nat { n * (n - 1) / 2 } method sum(n: nat) returns(s: nat) ensures s == calcSum(n + 1) { s := 0; var i := 0; while i < n decreases n - i invariant 0 <= i <= n invariant s == calcSum(i + 1) { i := i + 1; s := s + i; } }
function calcSum(n: nat) : nat { n * (n - 1) / 2 } method sum(n: nat) returns(s: nat) ensures s == calcSum(n + 1) { s := 0; var i := 0; while i < n { i := i + 1; s := s + i; } }
246
MFES_2021_tmp_tmpuljn8zd9_PracticalClasses_TP3_2_Insertion_Sort.dfy
// Sorts array 'a' using the insertion sort algorithm. method insertionSort(a: array<int>) modifies a ensures isSorted(a, 0, a.Length) ensures multiset(a[..]) == multiset(old(a[..])) { var i := 0; while i < a.Length decreases a.Length - i invariant 0 <= i <= a.Length invariant isSorted(a, 0, i) invariant multiset(a[..]) == multiset(old(a[..])) { var j := i; while j > 0 && a[j-1] > a[j] decreases j invariant 0 <= j <= i invariant multiset(a[..]) == multiset(old(a[..])) invariant forall l, r :: 0 <= l < r <= i && r != j ==> a[l] <= a[r] { a[j-1], a[j] := a[j], a[j-1]; j := j - 1; } i := i + 1; } } // Checks if array 'a' is sorted. predicate isSorted(a: array<int>, from: nat, to: nat) reads a requires 0 <= from <= to <= a.Length { forall i, j :: from <= i < j < to ==> a[i] <= a[j] } // Simple test case to check the postcondition method testInsertionSort() { var a := new int[] [ 9, 4, 3, 6, 8]; assert a[..] == [9, 4, 3, 6, 8]; insertionSort(a); assert a[..] == [3, 4, 6, 8, 9]; }
// Sorts array 'a' using the insertion sort algorithm. method insertionSort(a: array<int>) modifies a ensures isSorted(a, 0, a.Length) ensures multiset(a[..]) == multiset(old(a[..])) { var i := 0; while i < a.Length { var j := i; while j > 0 && a[j-1] > a[j] { a[j-1], a[j] := a[j], a[j-1]; j := j - 1; } i := i + 1; } } // Checks if array 'a' is sorted. predicate isSorted(a: array<int>, from: nat, to: nat) reads a requires 0 <= from <= to <= a.Length { forall i, j :: from <= i < j < to ==> a[i] <= a[j] } // Simple test case to check the postcondition method testInsertionSort() { var a := new int[] [ 9, 4, 3, 6, 8]; insertionSort(a); }
247
MFES_2021_tmp_tmpuljn8zd9_TheoreticalClasses_Power.dfy
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, MIEIC, MFES, 2020/21. */ // Initial specification/definition of x^n, recursive, functional style, // with time and space complexity O(n). function power(x: real, n: nat) : real decreases n { if n == 0 then 1.0 else x * power(x, n-1) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(x: real, n: nat) returns (p : real) ensures p == power(x, n) { // start with p = x^0 var i := 0; p := 1.0; // x ^ i // iterate until reaching p = x^n while i < n decreases n - i invariant 0 <= i <= n && p == power(x, i) { p := p * x; i := i + 1; } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(x: real, n: nat) returns (p : real) ensures p == power(x, n); decreases n; { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { distributiveProperty(x, n/2, n/2); // recall lemma here var temp := powerOpt(x, n/2); return temp * temp; } else { distributiveProperty(x, (n-1)/2, (n-1)/2); // recall lemma here var temp := powerOpt(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that powerOpt takes advantage of. // The annotation {:induction a} guides Dafny to prove the property // by automatic induction on 'a'. lemma {:induction a} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { // // To use the proof below, deactivate automatic induction, with {:induction false}. /* if a == 0 { // base case calc == { power(x, a) * power(x, b); power(x, 0) * power(x, b); // substitution 1.0 * power(x, b); // by the definition of power power(x, b); // neutral element of "*" power(x, a + b); // neutral element of "+" } } else { // recursive case, assuming property holds for a-1 (proof by induction) distributiveProperty(x, a-1, b); // now do the proof calc == { power(x, a) * power(x, b); (x * power(x, a-1)) * power(x, b); // by the definition of power x * (power(x, a-1) * power(x, b)); // associative property x * power(x, a + b - 1); // this same property for a-1 power(x, a + b); // definition of power } }*/ } // A simple test case to make sure the specification is adequate. method testPowerIter(){ var p1 := powerIter(2.0, 5); assert p1 == 32.0; } method testPowerOpt(){ var p1 := powerOpt(2.0, 5); assert p1 == 32.0; }
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, MIEIC, MFES, 2020/21. */ // Initial specification/definition of x^n, recursive, functional style, // with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(x: real, n: nat) returns (p : real) ensures p == power(x, n) { // start with p = x^0 var i := 0; p := 1.0; // x ^ i // iterate until reaching p = x^n while i < n { p := p * x; i := i + 1; } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(x: real, n: nat) returns (p : real) ensures p == power(x, n); { if n == 0 { return 1.0; } else if n == 1 { return x; } else if n % 2 == 0 { distributiveProperty(x, n/2, n/2); // recall lemma here var temp := powerOpt(x, n/2); return temp * temp; } else { distributiveProperty(x, (n-1)/2, (n-1)/2); // recall lemma here var temp := powerOpt(x, (n-1)/2); return temp * temp * x; } } // States the property x^a * x^b = x^(a+b), that powerOpt takes advantage of. // The annotation {:induction a} guides Dafny to prove the property // by automatic induction on 'a'. lemma {:induction a} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a + b) { // // To use the proof below, deactivate automatic induction, with {:induction false}. /* if a == 0 { // base case calc == { power(x, a) * power(x, b); power(x, 0) * power(x, b); // substitution 1.0 * power(x, b); // by the definition of power power(x, b); // neutral element of "*" power(x, a + b); // neutral element of "+" } } else { // recursive case, assuming property holds for a-1 (proof by induction) distributiveProperty(x, a-1, b); // now do the proof calc == { power(x, a) * power(x, b); (x * power(x, a-1)) * power(x, b); // by the definition of power x * (power(x, a-1) * power(x, b)); // associative property x * power(x, a + b - 1); // this same property for a-1 power(x, a + b); // definition of power } }*/ } // A simple test case to make sure the specification is adequate. method testPowerIter(){ var p1 := powerIter(2.0, 5); } method testPowerOpt(){ var p1 := powerOpt(2.0, 5); }
248
MFS_tmp_tmpmmnu354t_Praticas_TP9_Power.dfy
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, M.EIC, MFS, 2021/22. */ // Initial specification/definition of x^n, recursive, functional style, // with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(b: real, n: nat) returns (p : real) ensures p == power(b, n) { // start with p = b^0 p := 1.0; var i := 0; // iterate until reaching p = b^n while i < n invariant p == power(b, i) && 0 <= i <= n { p := p * b; i := i + 1; } } lemma {:induction e1} powDist(b: real, e1: nat, e2: nat) ensures power(b, e1+e2) == power(b, e1) * power(b, e2) {} lemma {:induction false} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a+b) { if a == 0 { assert power(x, a) * power(x, b) == 1.0 * power(x, b) == power(x, b) == power(x, a + b); } else { distributiveProperty(x, a-1, b); assert power(x, a) * power(x, b) == (x * power(x, a-1)) * power(x, b) == x * (power(x, a-1) * power(x, b)) == x * power(x, a - 1 + b) == power(x, a + b); } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(b: real, n: nat) returns (p : real) ensures p == power(b, n) { if n == 0 { return 1.0; } else if n % 2 == 0 { distributiveProperty(b, n/2, n/2); var r := powerOpt(b, n/2); return r * r; } else { distributiveProperty(b, (n-1)/2, (n-1)/2); var r := powerOpt(b, (n-1)/2); return r * r * b; } } // A simple test case to make sure the specification is adequate. method testPower() { var p1 := powerIter(2.0, 5); var p2 := powerOpt(2.0, 5); print "P1: ", p1, "\n"; print "P2: ", p2, "\n"; assert p1 == 32.0; assert p2 == 32.0; }
/* * Formal verification of O(n) and O(log n) algorithms to calculate the natural * power of a real number (x^n), illustrating the usage of lemmas. * FEUP, M.EIC, MFS, 2021/22. */ // Initial specification/definition of x^n, recursive, functional style, // with time and space complexity O(n). function power(x: real, n: nat) : real { if n == 0 then 1.0 else x * power(x, n-1) } // Iterative version, imperative, with time complexity O(n) and space complexity O(1). method powerIter(b: real, n: nat) returns (p : real) ensures p == power(b, n) { // start with p = b^0 p := 1.0; var i := 0; // iterate until reaching p = b^n while i < n { p := p * b; i := i + 1; } } lemma {:induction e1} powDist(b: real, e1: nat, e2: nat) ensures power(b, e1+e2) == power(b, e1) * power(b, e2) {} lemma {:induction false} distributiveProperty(x: real, a: nat, b: nat) ensures power(x, a) * power(x, b) == power(x, a+b) { if a == 0 { power(x, a) * power(x, b) == 1.0 * power(x, b) == power(x, b) == power(x, a + b); } else { distributiveProperty(x, a-1, b); power(x, a) * power(x, b) == (x * power(x, a-1)) * power(x, b) == x * (power(x, a-1) * power(x, b)) == x * power(x, a - 1 + b) == power(x, a + b); } } // Recursive version, imperative, with time and space complexity O(log n). method powerOpt(b: real, n: nat) returns (p : real) ensures p == power(b, n) { if n == 0 { return 1.0; } else if n % 2 == 0 { distributiveProperty(b, n/2, n/2); var r := powerOpt(b, n/2); return r * r; } else { distributiveProperty(b, (n-1)/2, (n-1)/2); var r := powerOpt(b, (n-1)/2); return r * r * b; } } // A simple test case to make sure the specification is adequate. method testPower() { var p1 := powerIter(2.0, 5); var p2 := powerOpt(2.0, 5); print "P1: ", p1, "\n"; print "P2: ", p2, "\n"; }
249
MFS_tmp_tmpmmnu354t_Testes anteriores_T2_ex5_2020_2.dfy
method leq(a: array<int>, b: array<int>) returns (result: bool) ensures result <==> (a.Length <= b.Length && a[..] == b[..a.Length]) || (exists k :: 0 <= k < a.Length && k < b.Length && a[..k] == b[..k] && a[k] < b[k]) { var i := 0; while i < a.Length && i < b.Length decreases a.Length - i invariant 0 <= i <= a.Length && 0 <= i <= b.Length invariant a[..i] == b[..i] { if a[i] < b[i] { return true; } else if a[i] > b[i] { return false; } else {i := i + 1; } } return a.Length <= b.Length; } method testLeq() { var b := new int[][1, 2]; var a1 := new int[][]; var r1 := leq(a1, b); assert r1; var a2 := new int[][1]; var r2 := leq(a2, b); assert r2; var a3 := new int[][1, 2]; var r3 := leq(a3, b); assert r3; var a4 := new int[][1, 1, 2]; var r4 := leq(a4, b); assert a4[1]<b[1] && r4; var a5 := new int[][1, 2, 3]; var r5 := leq(a5, b); assert !r5; var a6 := new int[][2]; var r6 := leq(a6, b); assert !r6; }
method leq(a: array<int>, b: array<int>) returns (result: bool) ensures result <==> (a.Length <= b.Length && a[..] == b[..a.Length]) || (exists k :: 0 <= k < a.Length && k < b.Length && a[..k] == b[..k] && a[k] < b[k]) { var i := 0; while i < a.Length && i < b.Length { if a[i] < b[i] { return true; } else if a[i] > b[i] { return false; } else {i := i + 1; } } return a.Length <= b.Length; } method testLeq() { var b := new int[][1, 2]; var a1 := new int[][]; var r1 := leq(a1, b); assert r1; var a2 := new int[][1]; var r2 := leq(a2, b); assert r2; var a3 := new int[][1, 2]; var r3 := leq(a3, b); assert r3; var a4 := new int[][1, 1, 2]; var r4 := leq(a4, b); assert a4[1]<b[1] && r4; var a5 := new int[][1, 2, 3]; var r5 := leq(a5, b); assert !r5; var a6 := new int[][2]; var r6 := leq(a6, b); assert !r6; }
250
MIEIC_mfes_tmp_tmpq3ho7nve_TP3_binary_search.dfy
// Checks if array 'a' is sorted. predicate isSorted(a: array<int>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Finds a value 'x' in a sorted array 'a', and returns its index, // or -1 if not found. method binarySearch(a: array<int>, x: int) returns (index: int) requires isSorted(a) ensures -1 <= index < a.Length ensures if index != -1 then a[index] == x else x !in a[..] //forall i :: 0 <= i < a.Length ==> a[i] != x { var low, high := 0, a.Length; while low < high decreases high - low invariant 0 <= low <= high <= a.Length && x !in a[..low] && x !in a[high..] { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return -1; } // Simple test cases to check the post-condition. method testBinarySearch() { var a := new int[] [1, 4, 4, 6, 8]; assert a[..] == [1, 4, 4, 6, 8]; var id1 := binarySearch(a, 6); assert a[3] == 6; // added assert id1 == 3; var id2 := binarySearch(a, 3); assert id2 == -1; var id3 := binarySearch(a, 4); assert a[1] == 4 && a[2] == 4; // added assert id3 in {1, 2}; } /* a) Identify adequate pre and post-conditions for this method, and encode them as “requires” and “ensures” clauses in Dafny. You can use the predicate below if needed. b) Identify an adequate loop variant and loop invariant, and encode them as “decreases” and “invariant” clauses in Dafny. */
// Checks if array 'a' is sorted. predicate isSorted(a: array<int>) reads a { forall i, j :: 0 <= i < j < a.Length ==> a[i] <= a[j] } // Finds a value 'x' in a sorted array 'a', and returns its index, // or -1 if not found. method binarySearch(a: array<int>, x: int) returns (index: int) requires isSorted(a) ensures -1 <= index < a.Length ensures if index != -1 then a[index] == x else x !in a[..] //forall i :: 0 <= i < a.Length ==> a[i] != x { var low, high := 0, a.Length; while low < high x !in a[..low] && x !in a[high..] { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return -1; } // Simple test cases to check the post-condition. method testBinarySearch() { var a := new int[] [1, 4, 4, 6, 8]; var id1 := binarySearch(a, 6); var id2 := binarySearch(a, 3); var id3 := binarySearch(a, 4); } /* a) Identify adequate pre and post-conditions for this method, and encode them as “requires” and “ensures” clauses in Dafny. You can use the predicate below if needed. b) Identify an adequate loop variant and loop invariant, and encode them as “decreases” and “invariant” clauses in Dafny. */
251
MIEIC_mfes_tmp_tmpq3ho7nve_exams_appeal_20_p4.dfy
function F(n: nat): nat { if n <= 2 then n else F(n-1) + F(n-3)} method calcF(n: nat) returns (res: nat) ensures res == F(n) { var a, b, c := 0, 1, 2; var i := 0; while i < n decreases n-i invariant 0 <= i <= n invariant a == F(i) && b == F(i+1) && c == F(i+2) { a, b, c := b, c, a + c; i := i + 1; } res := a; }
function F(n: nat): nat { if n <= 2 then n else F(n-1) + F(n-3)} method calcF(n: nat) returns (res: nat) ensures res == F(n) { var a, b, c := 0, 1, 2; var i := 0; while i < n { a, b, c := b, c, a + c; i := i + 1; } res := a; }
252
MIEIC_mfes_tmp_tmpq3ho7nve_exams_mt2_19_p4.dfy
function R(n: nat): nat { if n == 0 then 0 else if R(n-1) > n then R(n-1) - n else R(n-1) + n } method calcR(n: nat) returns (r: nat) ensures r == R(n) { r := 0; var i := 0; while i < n decreases n-i invariant 0 <= i <= n invariant r == R(i) { i := i + 1; if r > i { r := r - i; } else { r := r + i; } } }
function R(n: nat): nat { if n == 0 then 0 else if R(n-1) > n then R(n-1) - n else R(n-1) + n } method calcR(n: nat) returns (r: nat) ensures r == R(n) { r := 0; var i := 0; while i < n { i := i + 1; if r > i { r := r - i; } else { r := r + i; } } }
253
MIEIC_mfes_tmp_tmpq3ho7nve_exams_mt2_19_p5.dfy
type T = int // example // Partitions a nonempty array 'a', by reordering the elements in the array, // so that elements smaller than a chosen pivot are placed to the left of the // pivot, and values greater or equal than the pivot are placed to the right of // the pivot. Returns the pivot position. method partition(a: array<T>) returns(pivotPos: int) requires a.Length > 0 ensures 0 <= pivotPos < a.Length ensures forall i :: 0 <= i < pivotPos ==> a[i] < a[pivotPos] ensures forall i :: pivotPos < i < a.Length ==> a[i] >= a[pivotPos] ensures multiset(a[..]) == multiset(old(a[..])) modifies a { pivotPos := a.Length - 1; // chooses pivot at end of array var i := 0; // index that separates values smaller than pivot (0 to i-1), // and values greater or equal than pivot (i to j-1) var j := 0; // index to scan the array // Scan the array and move elements as needed while j < a.Length-1 decreases a.Length-1-j invariant 0 <= i <= j < a.Length invariant forall k :: 0 <= k < i ==> a[k] < a[pivotPos] invariant forall k :: i <= k < j ==> a[k] >= a[pivotPos] invariant multiset(a[..]) == multiset(old(a[..])) { if a[j] < a[pivotPos] { a[i], a[j] := a[j], a[i]; i := i + 1; } j := j+1; } // Swap pivot to the 'mid' of the array a[a.Length-1], a[i] := a[i], a[a.Length-1]; pivotPos := i; }
type T = int // example // Partitions a nonempty array 'a', by reordering the elements in the array, // so that elements smaller than a chosen pivot are placed to the left of the // pivot, and values greater or equal than the pivot are placed to the right of // the pivot. Returns the pivot position. method partition(a: array<T>) returns(pivotPos: int) requires a.Length > 0 ensures 0 <= pivotPos < a.Length ensures forall i :: 0 <= i < pivotPos ==> a[i] < a[pivotPos] ensures forall i :: pivotPos < i < a.Length ==> a[i] >= a[pivotPos] ensures multiset(a[..]) == multiset(old(a[..])) modifies a { pivotPos := a.Length - 1; // chooses pivot at end of array var i := 0; // index that separates values smaller than pivot (0 to i-1), // and values greater or equal than pivot (i to j-1) var j := 0; // index to scan the array // Scan the array and move elements as needed while j < a.Length-1 { if a[j] < a[pivotPos] { a[i], a[j] := a[j], a[i]; i := i + 1; } j := j+1; } // Swap pivot to the 'mid' of the array a[a.Length-1], a[i] := a[i], a[a.Length-1]; pivotPos := i; }
254
MIEIC_mfes_tmp_tmpq3ho7nve_exams_special_20_p5.dfy
type T = int // for demo purposes, but could be another type predicate sorted(a: array<T>, n: nat) requires n <= a.Length reads a { forall i,j :: 0 <= i < j < n ==> a[i] <= a[j] } // Use binary search to find an appropriate position to insert a value 'x' // in a sorted array 'a', so that it remains sorted. method binarySearch(a: array<T>, x: T) returns (index: int) requires sorted(a, a.Length) ensures sorted(a, a.Length) //ensures a[..] == old(a)[..] ensures 0 <= index <= a.Length //ensures forall i :: 0 <= i < index ==> a[i] <= x //ensures forall i :: index <= i < a.Length ==> a[i] >= x ensures index > 0 ==> a[index-1] <= x ensures index < a.Length ==> a[index] >= x { var low, high := 0, a.Length; while low < high decreases high-low invariant 0 <= low <= high <= a.Length invariant low > 0 ==> a[low-1] <= x invariant high < a.Length ==> a[high] >= x { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return low; } // Simple test cases to check the post-condition method testBinarySearch() { var a := new int[2] [1, 3]; var id0 := binarySearch(a, 0); assert id0 == 0; var id1 := binarySearch(a, 1); assert id1 in {0, 1}; var id2 := binarySearch(a, 2); assert id2 == 1; var id3 := binarySearch(a, 3); assert id3 in {1, 2}; var id4 := binarySearch(a, 4); assert id4 == 2; }
type T = int // for demo purposes, but could be another type predicate sorted(a: array<T>, n: nat) requires n <= a.Length reads a { forall i,j :: 0 <= i < j < n ==> a[i] <= a[j] } // Use binary search to find an appropriate position to insert a value 'x' // in a sorted array 'a', so that it remains sorted. method binarySearch(a: array<T>, x: T) returns (index: int) requires sorted(a, a.Length) ensures sorted(a, a.Length) //ensures a[..] == old(a)[..] ensures 0 <= index <= a.Length //ensures forall i :: 0 <= i < index ==> a[i] <= x //ensures forall i :: index <= i < a.Length ==> a[i] >= x ensures index > 0 ==> a[index-1] <= x ensures index < a.Length ==> a[index] >= x { var low, high := 0, a.Length; while low < high { var mid := low + (high - low) / 2; if { case a[mid] < x => low := mid + 1; case a[mid] > x => high := mid; case a[mid] == x => return mid; } } return low; } // Simple test cases to check the post-condition method testBinarySearch() { var a := new int[2] [1, 3]; var id0 := binarySearch(a, 0); var id1 := binarySearch(a, 1); var id2 := binarySearch(a, 2); var id3 := binarySearch(a, 3); var id4 := binarySearch(a, 4); }
255
Metodos_Formais_tmp_tmpbez22nnn_Aula_2_ex1.dfy
method Mult(x:nat, y:nat) returns (r: nat) ensures r == x * y { var m := x; var n := y; r:=0; while m > 0 invariant m >= 0 invariant m*n+r == x*y { r := r + n; m := m - 1; } return r; }
method Mult(x:nat, y:nat) returns (r: nat) ensures r == x * y { var m := x; var n := y; r:=0; while m > 0 { r := r + n; m := m - 1; } return r; }
256
Metodos_Formais_tmp_tmpbez22nnn_Aula_2_ex2.dfy
function Potencia(x: nat, y: nat): nat { if y == 0 then 1 else x * Potencia(x, y-1) } method Pot(x: nat, y: nat) returns (r: nat) ensures r == Potencia(x,y) { var b := x; var e := y; r := 1; while e > 0 invariant Potencia(b, e) * r == Potencia(x,y) { r := b * r; e := e - 1; } return r; }
function Potencia(x: nat, y: nat): nat { if y == 0 then 1 else x * Potencia(x, y-1) } method Pot(x: nat, y: nat) returns (r: nat) ensures r == Potencia(x,y) { var b := x; var e := y; r := 1; while e > 0 { r := b * r; e := e - 1; } return r; }
257
Metodos_Formais_tmp_tmpbez22nnn_Aula_4_ex1.dfy
predicate Par(n:int) { n % 2 == 0 } method FazAlgo (a:int, b:int) returns (x:int, y:int) requires a >= b && Par (a-b) { x := a; y := b; while x != y invariant x >= y invariant Par(x-y) decreases x-y { x := x - 1; y := y + 1; } }
predicate Par(n:int) { n % 2 == 0 } method FazAlgo (a:int, b:int) returns (x:int, y:int) requires a >= b && Par (a-b) { x := a; y := b; while x != y { x := x - 1; y := y + 1; } }
258
Metodos_Formais_tmp_tmpbez22nnn_Aula_4_ex3.dfy
function Fib(n:nat):nat { if n < 2 then n else Fib(n-2) + Fib(n-1) } method ComputeFib(n:nat) returns (x:nat) ensures x == Fib(n) { var i := 0; x := 0; var y := 1; while i < n decreases n - i invariant 0 <= i <= n invariant x == Fib(i) invariant y == Fib(i+1) { x, y := y, x + y; i := i + 1; } } method Teste() { var n := 3; var f := ComputeFib(n); assert f == 2; }
function Fib(n:nat):nat { if n < 2 then n else Fib(n-2) + Fib(n-1) } method ComputeFib(n:nat) returns (x:nat) ensures x == Fib(n) { var i := 0; x := 0; var y := 1; while i < n { x, y := y, x + y; i := i + 1; } } method Teste() { var n := 3; var f := ComputeFib(n); }
259
Metodos_Formais_tmp_tmpql2hwcsh_Arrays_explicacao.dfy
// Array<T> = visualização de um array // Uma busca ordenada em um array // Buscar: Array<Z>xZ -> Z (Z é inteiro) // Pré: True (pré-condição é sempre verdadeira) // Pos: R < 0 => Para todo i pertencente aos naturais(0 <= i < A.length => A[i] != X) e // 0 <= R < A.length => A[R] = x // // método em qualquer linguagem: // R = 0 // Enquanto(R < |A|) { // Se (A[R] == X) retorne E // R = R + 1 // } // retorne -1 // // X | R | |A| // 10 | 0 | 5 // 10 | 1 | 5 // 10 | 2 | // invariante detectada: 0 <= R <= |A| e Para todo i pertencente aos naturais(0 <= i < R => A[i] != X) // no dafy // forall = é o para todo logico // :: é igual ao tal que lógico // ==> é o então lógico // forall i :: 0 <= i < a.Length ==> a[i] != x (para todo i tal que i e maior ou igual a zero e menor que o tamanho do array, então a posição i do array a é diferente de x) method buscar(a:array<int>, x:int) returns (r:int) ensures r < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != x ensures 0 <= r < a.Length ==> a[r] == x { r := 0; while r < a.Length decreases a.Length - r //variante, decrescendo a cada passo com o r invariant 0 <= r <= a.Length //a invariante é quando nao é encontado o x depois de rodado todo o projeto invariant forall i :: 0 <= i < r ==> a[i] != x { if a[r] == x { return r; } r := r + 1; } return -1; }
// Array<T> = visualização de um array // Uma busca ordenada em um array // Buscar: Array<Z>xZ -> Z (Z é inteiro) // Pré: True (pré-condição é sempre verdadeira) // Pos: R < 0 => Para todo i pertencente aos naturais(0 <= i < A.length => A[i] != X) e // 0 <= R < A.length => A[R] = x // // método em qualquer linguagem: // R = 0 // Enquanto(R < |A|) { // Se (A[R] == X) retorne E // R = R + 1 // } // retorne -1 // // X | R | |A| // 10 | 0 | 5 // 10 | 1 | 5 // 10 | 2 | // invariante detectada: 0 <= R <= |A| e Para todo i pertencente aos naturais(0 <= i < R => A[i] != X) // no dafy // forall = é o para todo logico // :: é igual ao tal que lógico // ==> é o então lógico // forall i :: 0 <= i < a.Length ==> a[i] != x (para todo i tal que i e maior ou igual a zero e menor que o tamanho do array, então a posição i do array a é diferente de x) method buscar(a:array<int>, x:int) returns (r:int) ensures r < 0 ==> forall i :: 0 <= i < a.Length ==> a[i] != x ensures 0 <= r < a.Length ==> a[r] == x { r := 0; while r < a.Length { if a[r] == x { return r; } r := r + 1; } return -1; }
260
Metodos_Formais_tmp_tmpql2hwcsh_Arrays_somatorioArray.dfy
// Deve ser criado uma função explicando o que é um somatório // Somatorio: Array<N> -> N // Pre: True // Pos: Somatorio(A) = somatório de i = 0 até |A|-1 os valores das posições do array pelo i // // function é uma fórmula matemática, ele não possui variaveis globais // Soma: Array<N>xN -> N // { Soma(A,0) = A[0] // { Soma(A,i) = A[i] + soma(A, i-1) , se i > 0 // Teste // |A| = 4 // Soma(A, |A|-1) = Soma(A,3) // A[3] + Soma(A,2) // A[3] + A[2] + Soma(A,1) // A[3] + A[2] + A[1] + Soma(A,0) // A[3] + A[2] + A[1] + A[0] function soma(a:array<nat>, i:nat):nat requires i <= a.Length //Tem que dizer que o i só vai até um valor antes do tamanho do array reads a //serve para dizer que está sendo lido da memoria o array a (áreas de memória) { if i == 0 then 0 else a[i-1] + soma(a,i-1) } method somatorio(a:array<nat>) returns (s:nat) ensures s == soma(a, a.Length) { s := 0; for i := 0 to a.Length invariant s == soma(a,i) { s := s + a[i]; } }
// Deve ser criado uma função explicando o que é um somatório // Somatorio: Array<N> -> N // Pre: True // Pos: Somatorio(A) = somatório de i = 0 até |A|-1 os valores das posições do array pelo i // // function é uma fórmula matemática, ele não possui variaveis globais // Soma: Array<N>xN -> N // { Soma(A,0) = A[0] // { Soma(A,i) = A[i] + soma(A, i-1) , se i > 0 // Teste // |A| = 4 // Soma(A, |A|-1) = Soma(A,3) // A[3] + Soma(A,2) // A[3] + A[2] + Soma(A,1) // A[3] + A[2] + A[1] + Soma(A,0) // A[3] + A[2] + A[1] + A[0] function soma(a:array<nat>, i:nat):nat requires i <= a.Length //Tem que dizer que o i só vai até um valor antes do tamanho do array reads a //serve para dizer que está sendo lido da memoria o array a (áreas de memória) { if i == 0 then 0 else a[i-1] + soma(a,i-1) } method somatorio(a:array<nat>) returns (s:nat) ensures s == soma(a, a.Length) { s := 0; for i := 0 to a.Length { s := s + a[i]; } }
261
Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_fatorial2.dfy
function Fat(n:nat):nat { if n == 0 then 1 else n*Fat(n-1) } method Fatorial(n:nat) returns (f:nat) ensures f == Fat(n) { f := 1; var i := 1; while i <= n decreases n-i //variante invariant 1 <= i <= n+1 //invariante invariant f == Fat(i-1) //invariante { f := f * i; i := i + 1; } return f; } // i | n | variante // 1 | 3 | 2 // 2 | 3 | 1 // 3 | 3 | 0 // 4 | 3 | -1 // variante = n - i // então é usado o decreases n-1
function Fat(n:nat):nat { if n == 0 then 1 else n*Fat(n-1) } method Fatorial(n:nat) returns (f:nat) ensures f == Fat(n) { f := 1; var i := 1; while i <= n { f := f * i; i := i + 1; } return f; } // i | n | variante // 1 | 3 | 2 // 2 | 3 | 1 // 3 | 3 | 0 // 4 | 3 | -1 // variante = n - i // então é usado o decreases n-1
262
Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_fibonacci.dfy
// Provando fibonacci function Fib(n:nat):nat { if n < 2 then n else Fib(n-2) + Fib(n-1) } method ComputeFib(n:nat) returns (x:nat) ensures x == Fib(n) { var i := 0; x := 0; var y := 1; while i < n decreases n-i invariant 0 <= i <= n invariant x == Fib(i) invariant y == Fib(i+1) { x, y := y, x + y; //multiplas atribuições i := i + 1; } } // Fibonnaci // n | Fib // 0 | 0 // 1 | 1 // 2 | 1 // 3 | 2 // 4 | 3 // 5 | 5 // Teste da computação do Fibonnaci // i | n | x | y | n-1 // 0 | 3 | 0 | 1 | 3 // 1 | 3 | 1 | 1 | 2 // 2 | 3 | 1 | 2 | 1 // 3 | 3 | 2 | 3 | 0 // Variante: n - 1 // Invariante: x = Fib(i) = x sempre é o resultado do fibonnaci do valor de i // Invariante: 0 <= i <= n = i deve ter um valor entre 0 e o valor de n // Invariante: y = Fib(i+1) = o valor de y sempre vai ser o valor de fibonnaci mais um
// Provando fibonacci function Fib(n:nat):nat { if n < 2 then n else Fib(n-2) + Fib(n-1) } method ComputeFib(n:nat) returns (x:nat) ensures x == Fib(n) { var i := 0; x := 0; var y := 1; while i < n { x, y := y, x + y; //multiplas atribuições i := i + 1; } } // Fibonnaci // n | Fib // 0 | 0 // 1 | 1 // 2 | 1 // 3 | 2 // 4 | 3 // 5 | 5 // Teste da computação do Fibonnaci // i | n | x | y | n-1 // 0 | 3 | 0 | 1 | 3 // 1 | 3 | 1 | 1 | 2 // 2 | 3 | 1 | 2 | 1 // 3 | 3 | 2 | 3 | 0 // Variante: n - 1 // Invariante: x = Fib(i) = x sempre é o resultado do fibonnaci do valor de i // Invariante: 0 <= i <= n = i deve ter um valor entre 0 e o valor de n // Invariante: y = Fib(i+1) = o valor de y sempre vai ser o valor de fibonnaci mais um
263
Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_multiplicador.dfy
// Exemplo de invariantes // Invariante significa que o valor não muda desde a pré-condição até a pós-condição method Mult(x:nat, y:nat) returns (r:nat) ensures r == x * y { // parâmetros de entrada são imutáveis, por isso // é preciso a atribuir a variáveis locais para usar em blocos de códigos para mudar var m := x; var n := y; r := 0; while m > 0 invariant m >= 0 invariant m*n+r == x*y { r := r + n; m := m -1; } return r; } // Teste do método para encontrar a invariante // x | y | m | n | r // 5 | 3 | 5 | 3 | 0 // 5 | 3 | 4 | 3 | 3 // 5 | 3 | 3 | 3 | 6 // 5 | 3 | 2 | 3 | 9 // 5 | 3 | 1 | 3 | 12 // 5 | 3 | 0 | 3 | 15 // vimos o seguinte: // m * n + r = x * y // 5 * 3 + 0 (15) = 5 * 3 (15) // portanto a fórmula m*n+r == x*y é uma invariante // mas só isso não serve, o m ele é maior ou igual a zero quando acaba o while // por isso, também é a invariante que necessita // com isso dizemos para o programa as alterações do m de maior ou igual a zero // e mostramos a função encontrada que alterava o valor de m e n das variaveis criadas // SE OS ALGORITMOS TIVEREM REPETIÇÃO OU RECURSÃO, DEVEM SER MOSTRADOS QUAIS SÃO AS INVARIANTES // OU SEJA, OS VALORES QUE NÃO ESTÃO SENDO MUDADOS E COLOCAR A FÓRMULA DELE COMO ACIMA
// Exemplo de invariantes // Invariante significa que o valor não muda desde a pré-condição até a pós-condição method Mult(x:nat, y:nat) returns (r:nat) ensures r == x * y { // parâmetros de entrada são imutáveis, por isso // é preciso a atribuir a variáveis locais para usar em blocos de códigos para mudar var m := x; var n := y; r := 0; while m > 0 { r := r + n; m := m -1; } return r; } // Teste do método para encontrar a invariante // x | y | m | n | r // 5 | 3 | 5 | 3 | 0 // 5 | 3 | 4 | 3 | 3 // 5 | 3 | 3 | 3 | 6 // 5 | 3 | 2 | 3 | 9 // 5 | 3 | 1 | 3 | 12 // 5 | 3 | 0 | 3 | 15 // vimos o seguinte: // m * n + r = x * y // 5 * 3 + 0 (15) = 5 * 3 (15) // portanto a fórmula m*n+r == x*y é uma invariante // mas só isso não serve, o m ele é maior ou igual a zero quando acaba o while // por isso, também é a invariante que necessita // com isso dizemos para o programa as alterações do m de maior ou igual a zero // e mostramos a função encontrada que alterava o valor de m e n das variaveis criadas // SE OS ALGORITMOS TIVEREM REPETIÇÃO OU RECURSÃO, DEVEM SER MOSTRADOS QUAIS SÃO AS INVARIANTES // OU SEJA, OS VALORES QUE NÃO ESTÃO SENDO MUDADOS E COLOCAR A FÓRMULA DELE COMO ACIMA
264
Metodos_Formais_tmp_tmpql2hwcsh_Invariantes_potencia.dfy
// Potência // deve ser especificado a potência, porque ele não existe n dafny // Função recursiva da potência function Potencia(x:nat, y:nat):nat { if y == 0 then 1 else x * Potencia(x,y-1) } // Quero agora implementar como uma função não recursiva method Pot(x:nat, y:nat) returns (r:nat) ensures r == Potencia(x,y) { r := 1; //sempre r começa com 1 var b := x; //base var e := y; //expoente while e > 0 invariant Potencia(b,e)*r == Potencia(x,y) { r := r * b; e := e - 1; } return r; } // Devemos sempre construir uma tabela para vermos passo a passo o processo // POT(2,3) // x | y | b | e | r | // 2 | 3 | 2 | 3 | 1 | // 2 | 3 | 2 | 2 | 1x2 | // 2 | 3 | 2 | 1 | 1x2x2 | // 2 | 3 | 2 | 0 | 1x2x2x2 | // temos que na invariante queremos a fórmula x^y // INV ... = x^y // vendo pelo que foi processado fica dando o seguinte // x | y | b | e | r | // 2 | 3 | 2 | 3 | 1 (2^0) | 2^3 x 2^0 = 2^3 // 2 | 3 | 2 | 2 | 1x2 (2^1) | 2^2 x 2^1 = 2^3 // 2 | 3 | 2 | 1 | 1x2x2 (2^2) | 2^1 x 2^2 = 2^3 // 2 | 3 | 2 | 0 | 1x2x2x2 (2^3)| 2^0 x 2^3 = 2^3 // portanto a base está sendo feito a potencia de e (usando o potencia) e multiplicado pelo valor de r // b^e * r // assim temos a fórmula: b^e * r = x^y // dai utilizamos a function potencia para construir a fórmula // Potencia(b,e)*r == Potencia(x,y)
// Potência // deve ser especificado a potência, porque ele não existe n dafny // Função recursiva da potência function Potencia(x:nat, y:nat):nat { if y == 0 then 1 else x * Potencia(x,y-1) } // Quero agora implementar como uma função não recursiva method Pot(x:nat, y:nat) returns (r:nat) ensures r == Potencia(x,y) { r := 1; //sempre r começa com 1 var b := x; //base var e := y; //expoente while e > 0 { r := r * b; e := e - 1; } return r; } // Devemos sempre construir uma tabela para vermos passo a passo o processo // POT(2,3) // x | y | b | e | r | // 2 | 3 | 2 | 3 | 1 | // 2 | 3 | 2 | 2 | 1x2 | // 2 | 3 | 2 | 1 | 1x2x2 | // 2 | 3 | 2 | 0 | 1x2x2x2 | // temos que na invariante queremos a fórmula x^y // INV ... = x^y // vendo pelo que foi processado fica dando o seguinte // x | y | b | e | r | // 2 | 3 | 2 | 3 | 1 (2^0) | 2^3 x 2^0 = 2^3 // 2 | 3 | 2 | 2 | 1x2 (2^1) | 2^2 x 2^1 = 2^3 // 2 | 3 | 2 | 1 | 1x2x2 (2^2) | 2^1 x 2^2 = 2^3 // 2 | 3 | 2 | 0 | 1x2x2x2 (2^3)| 2^0 x 2^3 = 2^3 // portanto a base está sendo feito a potencia de e (usando o potencia) e multiplicado pelo valor de r // b^e * r // assim temos a fórmula: b^e * r = x^y // dai utilizamos a function potencia para construir a fórmula // Potencia(b,e)*r == Potencia(x,y)
265
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_mod.dfy
ghost function f(n: nat): nat { if n == 0 then 1 else if n%2 == 0 then 1 + 2*f(n/2) else 2*f(n/2) } method mod(n:nat) returns (a:nat) ensures a == f(n) { var x:nat := 0; var y:nat := 1; var k:nat := n; while k > 0 invariant f(n) == x + y*f(k) invariant 0 <= k <= n decreases k { assert f(n) == x + y*f(k); if (k%2 == 0) { assert f(n) == x + y*f(k); assert f(n) == x + y*(1+2*f(k/2)); assert f(n) == x + y + 2*y*f(k/2); x := x + y; assert f(n) == x + 2*y*f(k/2); } else { assert f(n) == x + y*(2*f(k/2)); assert f(n) == x + 2*y*f(k/2); } y := 2*y; assert f(n) == x + y*f(k/2); k := k/2; assert f(n) == x + y*f(k); } assert k == 0; assert f(n) == x+y*f(0); assert f(n) == x+y; a := x+y; }
ghost function f(n: nat): nat { if n == 0 then 1 else if n%2 == 0 then 1 + 2*f(n/2) else 2*f(n/2) } method mod(n:nat) returns (a:nat) ensures a == f(n) { var x:nat := 0; var y:nat := 1; var k:nat := n; while k > 0 { if (k%2 == 0) { x := x + y; } else { } y := 2*y; k := k/2; } a := x+y; }
266
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_mod2.dfy
ghost function f2(n: nat): nat { if n == 0 then 0 else 5*f2(n/3) + n%4 } method mod2(n:nat) returns (a:nat) ensures a == f2(n) { var x:nat := 1; var y:nat := 0; var k:nat := n; while k > 0 invariant f2(n) == x*f2(k) + y invariant 0 <= k <= n decreases k { assert f2(n) == x*f2(k) + y; assert f2(n) == x*(5*f2(k/3) + k%4) + y; assert f2(n) == 5*x*f2(k/3) + x*(k%4) + y; y := x*(k%4) + y; assert f2(n) == 5*x*f2(k/3) + y; x := 5*x; assert f2(n) == x*f2(k/3) + y; k := k/3; assert f2(n) == x*f2(k) + y; } assert k == 0; assert f2(n) == x*f2(0) + y; assert f2(n) == x*0 + y; assert f2(n) == y; a := y; }
ghost function f2(n: nat): nat { if n == 0 then 0 else 5*f2(n/3) + n%4 } method mod2(n:nat) returns (a:nat) ensures a == f2(n) { var x:nat := 1; var y:nat := 0; var k:nat := n; while k > 0 { y := x*(k%4) + y; x := 5*x; k := k/3; } a := y; }
267
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_pow.dfy
ghost function pow(a: int, e: nat): int { if e == 0 then 1 else a*pow(a, e-1) } method Pow(a: nat, n: nat) returns (y: nat) ensures y == pow(a, n) { var x:nat := 1; var k:nat := 0; while k < n invariant x == pow(a, k) invariant 0 <= k <= n decreases n-k { assert x == pow(a, k); x := a*x; assert x == a*pow(a, k); assert x == pow(a, k+1); k := k + 1; assert x == pow(a, k); } assert k == n; y := x; assert y == pow(a, n); }
ghost function pow(a: int, e: nat): int { if e == 0 then 1 else a*pow(a, e-1) } method Pow(a: nat, n: nat) returns (y: nat) ensures y == pow(a, n) { var x:nat := 1; var k:nat := 0; while k < n { x := a*x; k := k + 1; } y := x; }
268
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_extra_sum.dfy
ghost function sum(n: nat): int { if n == 0 then 0 else n + sum(n - 1) } method Sum(n: nat) returns (s: int) ensures s == sum(n) { var x:nat := 0; var y:nat := 1; var k:nat := n; while k > 0 invariant sum(n) == x + y*sum(k) invariant 0 <= k <= n decreases k { assert sum(n) == x + y*sum(k); assert sum(n) == x + y*(k+sum(k-1)); assert sum(n) == x + y*k + y*sum(k-1); x := x + y*k; assert sum(n) == x + y*sum(k-1); assert sum(n) == x + y*sum(k-1); k := k-1; assert sum(n) == x + y*sum(k); } assert k == 0; assert sum(n) == x + y*sum(0); assert sum(n) == x + y*0; s := x; assert sum(n) == s; }
ghost function sum(n: nat): int { if n == 0 then 0 else n + sum(n - 1) } method Sum(n: nat) returns (s: int) ensures s == sum(n) { var x:nat := 0; var y:nat := 1; var k:nat := n; while k > 0 { x := x + y*k; k := k-1; } s := x; }
269
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p2.dfy
// problem 2: // name: Gabriele Berardi // s-number: s4878728 // table: XXX method problem2(p:int, q:int, X:int, Y:int) returns (r:int, s:int) requires p == 2*X + Y && q == X + 3 ensures r == X && s == Y { assert p == 2*X + Y && q == X + 3; r, s := p, q; assert r == 2*X + Y && s == X + 3; r := r - 2*s + 6; assert r == 2*X + Y-2*X-6 + 6 && s == X + 3; assert r == Y && s == X + 3; s := s - 3; assert r == Y && s == X; r,s := s, r; assert s == Y && r == X; }
// problem 2: // name: Gabriele Berardi // s-number: s4878728 // table: XXX method problem2(p:int, q:int, X:int, Y:int) returns (r:int, s:int) requires p == 2*X + Y && q == X + 3 ensures r == X && s == Y { r, s := p, q; r := r - 2*s + 6; s := s - 3; r,s := s, r; }
270
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p3.dfy
// problem 3: // name: ....... (fill in your name) // s-number: s....... (fill in your student number) // table: ....... (fill in your table number) method problem3(m:int, X:int) returns (r:int) requires X >= 0 && (2*m == 1 - X || m == X + 3) ensures r == X { assert X >= 0 && (X == 1 - 2*m || m-3 == X); r := m; assert X >= 0 && (1 - 2*r >= 0 || r-3 >= 0); if (1-2*r >= 0) { assert X >= 0 && 2*r == 1-X; r := 2*r; assert X >= 0 && r == 1-X; r := -r+1; } else { assert r == X + 3; r := r -3; } assert r == X; }
// problem 3: // name: ....... (fill in your name) // s-number: s....... (fill in your student number) // table: ....... (fill in your table number) method problem3(m:int, X:int) returns (r:int) requires X >= 0 && (2*m == 1 - X || m == X + 3) ensures r == X { r := m; if (1-2*r >= 0) { r := 2*r; r := -r+1; } else { r := r -3; } }
271
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p5.dfy
// problem 5: // name: Gabriele Berardi // s-number: s4878728 // table: XXXX ghost function f(n: int): int { if n < 0 then 0 else 3*f(n-5) + n } method problem5(n:nat) returns (x: int) ensures x == f(n) { var a := 1; var b := 0; var k := n; while k >= 0 invariant f(n) == a*f(k) + b invariant -5 <= k <= n decreases k { assert f(n) == a*f(k) + b; assert f(n) == a*(3*f(k-5)+k) + b; assert f(n) == 3*a*f(k-5) + a*k + b; b := a*k + b; assert f(n) == 3*a*f(k-5) + b; a := 3*a; assert f(n) == a*f(k-5) + b; k := k - 5; assert f(n) == a*f(k) + b; } assert k < 0; assert f(n) == a*f(k) + b; assert f(n) == a*0 + b; x := b; assert x== f(n); }
// problem 5: // name: Gabriele Berardi // s-number: s4878728 // table: XXXX ghost function f(n: int): int { if n < 0 then 0 else 3*f(n-5) + n } method problem5(n:nat) returns (x: int) ensures x == f(n) { var a := 1; var b := 0; var k := n; while k >= 0 { b := a*k + b; a := 3*a; k := k - 5; } x := b; }
272
Prog-Fun-Solutions_tmp_tmp7_gmnz5f_mockExam2_p6.dfy
// problem 6: // name: Gabriele Berardi // s-number: s4878728 // table: XXXXX ghost function f(n: int): int { if n <= 0 then 1 else n + f(n-1)*f(n-2) } ghost function fSum(n: nat): int { // give the body of this function // it should return Sum(i: 0<=i < n: f(i)) if n <= 0 then 0 else f(n-1) + fSum(n-1) } method problem6(n:nat) returns (a: int) ensures a == fSum(n) { a := 0; var k := 0; var x := 1; var y := 2; while k < n invariant 0 <= k <= n && x == f(k) && y == f(k+1) && a == fSum(k) decreases n-k { assert x == f(k) && y == f(k+1) && a == fSum(k); k := k + 1; assert x == f(k-1) && y == f(k) && a == fSum(k-1); assert x == f(k-1) && y == f(k) && a == fSum(k) - f(k-1); a := a + x; assert x == f(k-1) && y == f(k) && a == fSum(k) - f(k-1) + f(k-1); assert x == f(k-1) && y == f(k) && a == fSum(k); x, y := y, k+1 + x*y; assert x == f(k) && y == k+1+f(k-1)*f(k) && a == fSum(k); assert x == f(k) && y == k+1+f(k+1-2)*f(k+1-1) && a == fSum(k); assert x == f(k) && y == f(k+1) && a == fSum(k); } assert a == fSum(k); }
// problem 6: // name: Gabriele Berardi // s-number: s4878728 // table: XXXXX ghost function f(n: int): int { if n <= 0 then 1 else n + f(n-1)*f(n-2) } ghost function fSum(n: nat): int { // give the body of this function // it should return Sum(i: 0<=i < n: f(i)) if n <= 0 then 0 else f(n-1) + fSum(n-1) } method problem6(n:nat) returns (a: int) ensures a == fSum(n) { a := 0; var k := 0; var x := 1; var y := 2; while k < n { k := k + 1; a := a + x; x, y := y, k+1 + x*y; } }
273
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_ArrayMap.dfy
// RUN: /print:log.bpl method ArrayMap<A>(f: int -> A, a: array<A>) requires a != null requires forall j :: 0 <= j < a.Length ==> f.requires(j) requires forall j :: 0 <= j < a.Length ==> a !in f.reads(j) modifies a ensures forall j :: 0 <= j < a.Length ==> a[j] == f(j) { var i := 0; while i < a.Length invariant 0 <= i <= a.Length; invariant forall j :: 0 <= j < i ==> a[j] == f(j) { a[i] := f(i); i := i + 1; } } /*method GenericSort<A>(cmp: (A, A) -> bool, a: array<A>) requires a != null requires forall x, y :: a !in cmp.reads(x, y) requires forall x, y :: cmp.requires(x, y) modifies a ensures forall x, y :: cmp.requires(x, y) ensures forall x, y :: 0 <= x < y < a.Length ==> cmp(a[x], a[y]) { var i := 0; while i < a.Length modifies a { var j := i - 1; while j >= 0 && !cmp(a[j], a[i]) modifies a { a[i], a[j] := a[j], a[i]; j := j - 1; } i := i + 1; } }*/
// RUN: /print:log.bpl method ArrayMap<A>(f: int -> A, a: array<A>) requires a != null requires forall j :: 0 <= j < a.Length ==> f.requires(j) requires forall j :: 0 <= j < a.Length ==> a !in f.reads(j) modifies a ensures forall j :: 0 <= j < a.Length ==> a[j] == f(j) { var i := 0; while i < a.Length { a[i] := f(i); i := i + 1; } } /*method GenericSort<A>(cmp: (A, A) -> bool, a: array<A>) requires a != null requires forall x, y :: a !in cmp.reads(x, y) requires forall x, y :: cmp.requires(x, y) modifies a ensures forall x, y :: cmp.requires(x, y) ensures forall x, y :: 0 <= x < y < a.Length ==> cmp(a[x], a[y]) { var i := 0; while i < a.Length modifies a { var j := i - 1; while j >= 0 && !cmp(a[j], a[i]) modifies a { a[i], a[j] := a[j], a[i]; j := j - 1; } i := i + 1; } }*/
274
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_EvenPredicate.dfy
// RUN: /compile:0 /nologo function IsEven(a : int) : bool requires a >= 0 { if a == 0 then true else if a == 1 then false else IsEven(a - 2) } lemma EvenSquare(a : int) requires a >= 0 ensures IsEven(a) ==> IsEven(a * a) { if a >= 2 && IsEven(a) { EvenSquare(a - 2); assert a * a == (a - 2) * (a - 2) + 4 * a - 4; EvenDouble(2 * a - 2); EvenPlus((a - 2) * (a - 2), 4 * a - 4); } } lemma EvenDouble(a: int) requires a >= 0 ensures IsEven(a + a) { if a >= 2 { EvenDouble(a - 2); } } lemma {:induction x} EvenPlus(x: int, y: int) requires x >= 0 requires y >= 0 requires IsEven(x) requires IsEven(y) ensures IsEven(x + y) { if x >= 2 { EvenPlus(x - 2, y); } } /* lemma {:induction x} EvenTimes(x: int, y: int) requires x >= 0 requires y >= 0 requires IsEven(x) requires IsEven(y) ensures IsEven(x * y) { if x >= 2 { calc { IsEven(x * y); IsEven((x - 2) * y + 2 * y); { Check1(y); EvenPlus((x - 2) * y, 2 * y); } true; } } } */
// RUN: /compile:0 /nologo function IsEven(a : int) : bool requires a >= 0 { if a == 0 then true else if a == 1 then false else IsEven(a - 2) } lemma EvenSquare(a : int) requires a >= 0 ensures IsEven(a) ==> IsEven(a * a) { if a >= 2 && IsEven(a) { EvenSquare(a - 2); EvenDouble(2 * a - 2); EvenPlus((a - 2) * (a - 2), 4 * a - 4); } } lemma EvenDouble(a: int) requires a >= 0 ensures IsEven(a + a) { if a >= 2 { EvenDouble(a - 2); } } lemma {:induction x} EvenPlus(x: int, y: int) requires x >= 0 requires y >= 0 requires IsEven(x) requires IsEven(y) ensures IsEven(x + y) { if x >= 2 { EvenPlus(x - 2, y); } } /* lemma {:induction x} EvenTimes(x: int, y: int) requires x >= 0 requires y >= 0 requires IsEven(x) requires IsEven(y) ensures IsEven(x * y) { if x >= 2 { calc { IsEven(x * y); IsEven((x - 2) * y + 2 * y); { Check1(y); EvenPlus((x - 2) * y, 2 * y); } true; } } } */
275
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_GenericMax.dfy
method GenericMax<A>(cmp: (A, A) -> bool, a: array<A>) returns (max: A) requires a != null && a.Length > 0 requires forall x, y :: cmp.requires(x, y) requires forall x, y :: cmp(x, y) || cmp(y, x); requires forall x, y, z :: cmp(x, y) && cmp(y, z) ==> cmp(x, z); ensures forall x :: 0 <= x < a.Length ==> // uncommenting the following line causes the program to verify // assume cmp.requires(a[x], max); cmp(a[x], max) { max := a[0]; var i := 0; while i < a.Length invariant 0 <= i <= a.Length invariant forall x :: 0 <= x < i ==> cmp(a[x], max) { if !cmp(a[i], max) { max := a[i]; } i := i + 1; } }
method GenericMax<A>(cmp: (A, A) -> bool, a: array<A>) returns (max: A) requires a != null && a.Length > 0 requires forall x, y :: cmp.requires(x, y) requires forall x, y :: cmp(x, y) || cmp(y, x); requires forall x, y, z :: cmp(x, y) && cmp(y, z) ==> cmp(x, z); ensures forall x :: 0 <= x < a.Length ==> // uncommenting the following line causes the program to verify // assume cmp.requires(a[x], max); cmp(a[x], max) { max := a[0]; var i := 0; while i < a.Length { if !cmp(a[i], max) { max := a[i]; } i := i + 1; } }
276
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_InsertionSort.dfy
predicate sorted (a:array<int>, start:int, end:int) // all "before" end are sorted requires a!=null requires 0<=start<=end<=a.Length reads a { forall j,k:: start<=j<k<end ==> a[j]<=a[k] } method InsertionSort (a:array<int>) requires a!=null && a.Length>1 ensures sorted(a, 0, a.Length) modifies a { var up := 1; while (up < a.Length) // outer loop invariant 1 <= up <= a.Length invariant sorted(a,0,up) { var down := up-1; var temp := a[up]; while down >= 0 && a[down+1] < a[down] // inner loop invariant forall j,k | 0 <= j < k < up+1 && k != down+1 :: a[j]<=a[k] { a[down],a[down+1] := a[down+1],a[down]; down := down-1; } up := up+1; } } method Main(){ var a := new int[5]; a[0],a[1],a[2],a[3],a[4] := 3,2,5,1,8; InsertionSort(a); print a[..]; }
predicate sorted (a:array<int>, start:int, end:int) // all "before" end are sorted requires a!=null requires 0<=start<=end<=a.Length reads a { forall j,k:: start<=j<k<end ==> a[j]<=a[k] } method InsertionSort (a:array<int>) requires a!=null && a.Length>1 ensures sorted(a, 0, a.Length) modifies a { var up := 1; while (up < a.Length) // outer loop { var down := up-1; var temp := a[up]; while down >= 0 && a[down+1] < a[down] // inner loop { a[down],a[down+1] := a[down+1],a[down]; down := down-1; } up := up+1; } } method Main(){ var a := new int[5]; a[0],a[1],a[2],a[3],a[4] := 3,2,5,1,8; InsertionSort(a); print a[..]; }
277
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_MatrixMultiplication.dfy
function RowColumnProduct(m1: array2<int>, m2: array2<int>, row: nat, column: nat): int reads m1 reads m2 requires m1 != null && m2 != null && m1.Length1 == m2.Length0 requires row < m1.Length0 && column < m2.Length1 { RowColumnProductFrom(m1, m2, row, column, 0) } function RowColumnProductFrom(m1: array2<int>, m2: array2<int>, row: nat, column: nat, k: nat): int reads m1 reads m2 requires m1 != null && m2 != null && k <= m1.Length1 == m2.Length0 requires row < m1.Length0 && column < m2.Length1 decreases m1.Length1 - k { if k == m1.Length1 then 0 else m1[row,k]*m2[k,column] + RowColumnProductFrom(m1, m2, row, column, k+1) } method multiply(m1: array2<int>, m2: array2<int>) returns (m3: array2<int>) requires m1 != null && m2 != null requires m1.Length1 == m2.Length0 ensures m3 != null && m3.Length0 == m1.Length0 && m3.Length1 == m2.Length1 ensures forall i, j | 0 <= i < m3.Length0 && 0 <= j < m3.Length1 :: m3[i, j] == RowColumnProduct(m1, m2, i, j) { m3 := new int[m1.Length0, m2.Length1]; var i := 0; while i < m1.Length0 invariant 0 <= i <= m1.Length0 invariant forall i', j' | 0 <= i' < i && 0 <= j' < m2.Length1 :: m3[i',j'] == RowColumnProduct(m1, m2, i', j') { var j := 0; while j < m2.Length1 invariant 0 <= j <= m2.Length1 invariant forall i', j' | 0 <= i' < i && 0 <= j' < m2.Length1 :: m3[i',j'] == RowColumnProduct(m1, m2, i', j') invariant forall j' | 0 <= j' < j :: m3[i,j'] == RowColumnProduct(m1, m2, i, j') { var k :=0; m3[i, j] := 0; while k < m1.Length1 invariant 0 <= k <= m1.Length1 invariant forall i', j' | 0 <= i' < i && 0 <= j' < m2.Length1 :: m3[i',j'] == RowColumnProduct(m1, m2, i', j') invariant forall j' | 0 <= j' < j :: m3[i,j'] == RowColumnProduct(m1, m2, i, j') invariant RowColumnProduct(m1, m2, i, j) == m3[i,j] + RowColumnProductFrom(m1, m2, i, j, k) { m3[i,j] := m3[i,j] + m1[i,k] * m2[k,j]; k := k+1; } j := j+1; } i := i+1; } }
function RowColumnProduct(m1: array2<int>, m2: array2<int>, row: nat, column: nat): int reads m1 reads m2 requires m1 != null && m2 != null && m1.Length1 == m2.Length0 requires row < m1.Length0 && column < m2.Length1 { RowColumnProductFrom(m1, m2, row, column, 0) } function RowColumnProductFrom(m1: array2<int>, m2: array2<int>, row: nat, column: nat, k: nat): int reads m1 reads m2 requires m1 != null && m2 != null && k <= m1.Length1 == m2.Length0 requires row < m1.Length0 && column < m2.Length1 { if k == m1.Length1 then 0 else m1[row,k]*m2[k,column] + RowColumnProductFrom(m1, m2, row, column, k+1) } method multiply(m1: array2<int>, m2: array2<int>) returns (m3: array2<int>) requires m1 != null && m2 != null requires m1.Length1 == m2.Length0 ensures m3 != null && m3.Length0 == m1.Length0 && m3.Length1 == m2.Length1 ensures forall i, j | 0 <= i < m3.Length0 && 0 <= j < m3.Length1 :: m3[i, j] == RowColumnProduct(m1, m2, i, j) { m3 := new int[m1.Length0, m2.Length1]; var i := 0; while i < m1.Length0 m3[i',j'] == RowColumnProduct(m1, m2, i', j') { var j := 0; while j < m2.Length1 m3[i',j'] == RowColumnProduct(m1, m2, i', j') m3[i,j'] == RowColumnProduct(m1, m2, i, j') { var k :=0; m3[i, j] := 0; while k < m1.Length1 m3[i',j'] == RowColumnProduct(m1, m2, i', j') m3[i,j'] == RowColumnProduct(m1, m2, i, j') m3[i,j] + RowColumnProductFrom(m1, m2, i, j, k) { m3[i,j] := m3[i,j] + m1[i,k] * m2[k,j]; k := k+1; } j := j+1; } i := i+1; } }
278
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_Modules.dfy
// RUN: /compile:1 abstract module Interface { type T function F(): T predicate P(x: T) lemma FP() ensures P(F()) } module Implementation refines Interface { predicate P(x: T) { false } } abstract module User { import I : Interface lemma Main() ensures I.P(I.F()); { I.FP(); assert I.P(I.F()); } } module Main refines User { import I = Implementation lemma Main() ensures I.P(I.F()) { I.FP(); assert false; } }
// RUN: /compile:1 abstract module Interface { type T function F(): T predicate P(x: T) lemma FP() ensures P(F()) } module Implementation refines Interface { predicate P(x: T) { false } } abstract module User { import I : Interface lemma Main() ensures I.P(I.F()); { I.FP(); } } module Main refines User { import I = Implementation lemma Main() ensures I.P(I.F()) { I.FP(); } }
279
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_OneHundredPrisonersAndALightbulb.dfy
// RUN: /compile:0 /nologo method CardinalitySubsetLt<T>(A: set<T>, B: set<T>) requires A < B ensures |A| < |B| decreases B { var b :| b in B && b !in A; var B' := B - {b}; assert |B| == |B'| + 1; if A < B' { CardinalitySubsetLt(A, B'); } else { assert A == B'; } } method strategy<T>(P: set<T>, Special: T) returns (count: int) requires |P| > 1 && Special in P ensures count == |P| - 1 decreases * { count := 0; var I := {}; var S := {}; var switch := false; while count < |P| - 1 invariant count <= |P| - 1 invariant count > 0 ==> Special in I invariant Special !in S && S < P && S <= I <= P invariant if switch then |S| == count + 1 else |S| == count decreases * { var p :| p in P; I := I + {p}; if p == Special { if switch { switch := false; count := count + 1; } } else { if p !in S && !switch { S := S + {p}; switch := true; } } } CardinalitySubsetLt(S, I); if I < P { CardinalitySubsetLt(I, P); } assert P <= I; assert I == P; }
// RUN: /compile:0 /nologo method CardinalitySubsetLt<T>(A: set<T>, B: set<T>) requires A < B ensures |A| < |B| { var b :| b in B && b !in A; var B' := B - {b}; if A < B' { CardinalitySubsetLt(A, B'); } else { } } method strategy<T>(P: set<T>, Special: T) returns (count: int) requires |P| > 1 && Special in P ensures count == |P| - 1 { count := 0; var I := {}; var S := {}; var switch := false; while count < |P| - 1 { var p :| p in P; I := I + {p}; if p == Special { if switch { switch := false; count := count + 1; } } else { if p !in S && !switch { S := S + {p}; switch := true; } } } CardinalitySubsetLt(S, I); if I < P { CardinalitySubsetLt(I, P); } }
280
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_Percentile.dfy
// Sum of elements of A from indices 0 to end. // end is inclusive! (not James's normal way of thinking!!) function SumUpto(A: array<real>, end: int): real requires -1 <= end < A.Length reads A { if end == -1 then 0.0 else A[end] + SumUpto(A, end-1) } function Sum(A: array<real>): real reads A { SumUpto(A, A.Length-1) } method Percentile(p: real, A: array<real>, total: real) returns (i: int) requires forall i | 0 <= i < A.Length :: A[i] > 0.0 requires 0.0 <= p <= 100.0 requires total == Sum(A) requires total > 0.0 ensures -1 <= i < A.Length ensures SumUpto(A, i) <= (p/100.0) * total ensures i+1 < A.Length ==> SumUpto(A, i+1) > (p/100.0) * total { i := -1; var s: real := 0.0; while i+1 != A.Length && s + A[i+1] <= (p/100.0) * total invariant -1 <= i < A.Length invariant s == SumUpto(A, i) invariant s <= (p/100.0) * total { i := i + 1; s := s + A[i]; } } // example showing that, with the original postcondition, the answer is non-unique! method PercentileNonUniqueAnswer() returns (p: real, A: array<real>, total: real, i1: int, i2: int) ensures forall i | 0 <= i < A.Length :: A[i] > 0.0 ensures 0.0 <= p <= 100.0 ensures total == Sum(A) ensures total > 0.0 ensures -1 <= i1 < A.Length ensures SumUpto(A, i1) <= (p/100.0) * total ensures i1+1 < A.Length ==> SumUpto(A, i1+1) >= (p/100.0) * total ensures -1 <= i2 < A.Length ensures SumUpto(A, i2) <= (p/100.0) * total ensures i2+1 < A.Length ==> SumUpto(A, i2+1) >= (p/100.0) * total ensures i1 != i2 { p := 100.0; A := new real[1]; A[0] := 1.0; total := 1.0; assert SumUpto(A, 0) == 1.0; i1 := -1; i2 := 0; } // proof that, with the corrected postcondition, the answer is unique lemma PercentileUniqueAnswer(p: real, A: array<real>, total: real, i1: int, i2: int) requires forall i | 0 <= i < A.Length :: A[i] > 0.0 requires 0.0 <= p <= 100.0 requires total == Sum(A) requires total > 0.0 requires -1 <= i1 < A.Length requires SumUpto(A, i1) <= (p/100.0) * total requires i1+1 < A.Length ==> SumUpto(A, i1+1) > (p/100.0) * total requires -1 <= i2 < A.Length requires SumUpto(A, i2) <= (p/100.0) * total requires i2+1 < A.Length ==> SumUpto(A, i2+1) > (p/100.0) * total decreases if i2 < i1 then 1 else 0 // wlog i1 <= i2 ensures i1 == i2 { if i1+1< i2 { SumUpto_increase(A, i1+1, i2); } } // lemma for previous proof: when an array has strictly positive elements, the // sums strictly increase left to right lemma SumUpto_increase(A: array<real>, end1: int, end2: int) requires forall i | 0 <= i < A.Length :: A[i] > 0.0 requires -1 <= end1 < A.Length requires -1 <= end2 < A.Length requires end1 < end2 ensures SumUpto(A, end1) < SumUpto(A, end2) {}
// Sum of elements of A from indices 0 to end. // end is inclusive! (not James's normal way of thinking!!) function SumUpto(A: array<real>, end: int): real requires -1 <= end < A.Length reads A { if end == -1 then 0.0 else A[end] + SumUpto(A, end-1) } function Sum(A: array<real>): real reads A { SumUpto(A, A.Length-1) } method Percentile(p: real, A: array<real>, total: real) returns (i: int) requires forall i | 0 <= i < A.Length :: A[i] > 0.0 requires 0.0 <= p <= 100.0 requires total == Sum(A) requires total > 0.0 ensures -1 <= i < A.Length ensures SumUpto(A, i) <= (p/100.0) * total ensures i+1 < A.Length ==> SumUpto(A, i+1) > (p/100.0) * total { i := -1; var s: real := 0.0; while i+1 != A.Length && s + A[i+1] <= (p/100.0) * total { i := i + 1; s := s + A[i]; } } // example showing that, with the original postcondition, the answer is non-unique! method PercentileNonUniqueAnswer() returns (p: real, A: array<real>, total: real, i1: int, i2: int) ensures forall i | 0 <= i < A.Length :: A[i] > 0.0 ensures 0.0 <= p <= 100.0 ensures total == Sum(A) ensures total > 0.0 ensures -1 <= i1 < A.Length ensures SumUpto(A, i1) <= (p/100.0) * total ensures i1+1 < A.Length ==> SumUpto(A, i1+1) >= (p/100.0) * total ensures -1 <= i2 < A.Length ensures SumUpto(A, i2) <= (p/100.0) * total ensures i2+1 < A.Length ==> SumUpto(A, i2+1) >= (p/100.0) * total ensures i1 != i2 { p := 100.0; A := new real[1]; A[0] := 1.0; total := 1.0; i1 := -1; i2 := 0; } // proof that, with the corrected postcondition, the answer is unique lemma PercentileUniqueAnswer(p: real, A: array<real>, total: real, i1: int, i2: int) requires forall i | 0 <= i < A.Length :: A[i] > 0.0 requires 0.0 <= p <= 100.0 requires total == Sum(A) requires total > 0.0 requires -1 <= i1 < A.Length requires SumUpto(A, i1) <= (p/100.0) * total requires i1+1 < A.Length ==> SumUpto(A, i1+1) > (p/100.0) * total requires -1 <= i2 < A.Length requires SumUpto(A, i2) <= (p/100.0) * total requires i2+1 < A.Length ==> SumUpto(A, i2+1) > (p/100.0) * total ensures i1 == i2 { if i1+1< i2 { SumUpto_increase(A, i1+1, i2); } } // lemma for previous proof: when an array has strictly positive elements, the // sums strictly increase left to right lemma SumUpto_increase(A: array<real>, end1: int, end2: int) requires forall i | 0 <= i < A.Length :: A[i] > 0.0 requires -1 <= end1 < A.Length requires -1 <= end2 < A.Length requires end1 < end2 ensures SumUpto(A, end1) < SumUpto(A, end2) {}
281
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_Refinement.dfy
// RUN: /nologo /rlimit:10000000 /noNLarith abstract module Interface { function addSome(n: nat): nat ensures addSome(n) > n } abstract module Mod { import A : Interface method m() { assert 6 <= A.addSome(5); print "Test\n"; } } module Implementation refines Interface { function addSome(n: nat): nat ensures addSome(n) == n + 1 { n + 1 } } module Mod2 refines Mod { import A = Implementation } method Main() { Mod2.m(); }
// RUN: /nologo /rlimit:10000000 /noNLarith abstract module Interface { function addSome(n: nat): nat ensures addSome(n) > n } abstract module Mod { import A : Interface method m() { print "Test\n"; } } module Implementation refines Interface { function addSome(n: nat): nat ensures addSome(n) == n + 1 { n + 1 } } module Mod2 refines Mod { import A = Implementation } method Main() { Mod2.m(); }
282
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_ReverseString.dfy
// RUN: /compile:0 predicate reversed (arr : array<char>, outarr: array<char>) requires arr != null && outarr != null //requires 0<=k<=arr.Length-1 requires arr.Length == outarr.Length reads arr, outarr { forall k :: 0<=k<=arr.Length-1 ==> outarr[k] == arr[(arr.Length-1-k)] } method yarra(arr : array<char>) returns (outarr : array<char>) requires arr != null && arr.Length > 0 ensures outarr != null && arr.Length == outarr.Length && reversed(arr,outarr) { var i:= 0; var j:= arr.Length-1; outarr := new char[arr.Length]; outarr[0] := arr[j]; i := i+1; j := j-1; while i<arr.Length && 0<=j<arr.Length invariant 0<=i<=arr.Length invariant j == arr.Length - 1 - i invariant forall k | 0 <= k < i :: outarr[k] == arr[arr.Length-1-k] decreases arr.Length-i, j { outarr[i] := arr[j]; i:=i+1; j:=j-1; } //return outarr; } method Main() { var s := ['a','b','a','b','a','b','a','b','a','b','a','b']; var a,b,c,d := new char[5], new char[5], new char[5], new char[5]; a[0], a[1], a[2], a[3], a[4] := 'y', 'a', 'r', 'r', 'a'; d[0], d[1], d[2], d[3], d[4] := 'y', 'a', 'r', 'r', 'a'; b := yarra(a); c := yarra(b); assert c[..] == a[..]; //assert c.Length > -2; //assert d[0] == a[0]; //print c; print a; }
// RUN: /compile:0 predicate reversed (arr : array<char>, outarr: array<char>) requires arr != null && outarr != null //requires 0<=k<=arr.Length-1 requires arr.Length == outarr.Length reads arr, outarr { forall k :: 0<=k<=arr.Length-1 ==> outarr[k] == arr[(arr.Length-1-k)] } method yarra(arr : array<char>) returns (outarr : array<char>) requires arr != null && arr.Length > 0 ensures outarr != null && arr.Length == outarr.Length && reversed(arr,outarr) { var i:= 0; var j:= arr.Length-1; outarr := new char[arr.Length]; outarr[0] := arr[j]; i := i+1; j := j-1; while i<arr.Length && 0<=j<arr.Length { outarr[i] := arr[j]; i:=i+1; j:=j-1; } //return outarr; } method Main() { var s := ['a','b','a','b','a','b','a','b','a','b','a','b']; var a,b,c,d := new char[5], new char[5], new char[5], new char[5]; a[0], a[1], a[2], a[3], a[4] := 'y', 'a', 'r', 'r', 'a'; d[0], d[1], d[2], d[3], d[4] := 'y', 'a', 'r', 'r', 'a'; b := yarra(a); c := yarra(b); //assert c.Length > -2; //assert d[0] == a[0]; //print c; print a; }
283
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_advanced examples_demo.dfy
method Partition(a: array<int>) returns (lo: int, hi: int) modifies a ensures 0 <= lo <= hi <= a.Length ensures forall x | 0 <= x < lo :: a[x] < 0 ensures forall x | lo <= x < hi :: a[x] == 0 ensures forall x | hi <= x < a.Length :: a[x] > 0 { var i := 0; var j := a.Length; var k := a.Length; while i < j invariant 0 <= i <= j <= k <= a.Length invariant forall x | 0 <= x < i :: a[x] < 0 invariant forall x | j <= x < k :: a[x] == 0 invariant forall x | k <= x < a.Length :: a[x] > 0 { if a[i] < 0 { i := i + 1; } else if a[i] == 0 { var current := a[i]; a[i] := a[j-1]; a[j-1] := current; j := j - 1; } else { assert a[i] > 0; var current := a[i]; a[i] := a[j-1]; a[j-1] := a[k-1]; a[k-1] := current; j := j - 1; k := k - 1; } } return i, k; }
method Partition(a: array<int>) returns (lo: int, hi: int) modifies a ensures 0 <= lo <= hi <= a.Length ensures forall x | 0 <= x < lo :: a[x] < 0 ensures forall x | lo <= x < hi :: a[x] == 0 ensures forall x | hi <= x < a.Length :: a[x] > 0 { var i := 0; var j := a.Length; var k := a.Length; while i < j { if a[i] < 0 { i := i + 1; } else if a[i] == 0 { var current := a[i]; a[i] := a[j-1]; a[j-1] := current; j := j - 1; } else { var current := a[i]; a[i] := a[j-1]; a[j-1] := a[k-1]; a[k-1] := current; j := j - 1; k := k - 1; } } return i, k; }
284
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_ProgramProofs_ch15.dfy
predicate SplitPoint(a: array<int>, n: int) reads a requires 0 <= n <= n { forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] } method SelectionSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { var n := 0; while n != a.Length invariant 0 <= n <= a.Length invariant forall i,j :: 0 <= i < j < n ==> a[i] <= a[j] // invariant forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] invariant SplitPoint(a, n) invariant multiset(a[..]) == old(multiset(a[..])) { var mindex, m := n, n; while m != a.Length invariant n <= m <= a.Length && n <= mindex < a.Length invariant forall i :: n <= i < m ==> a[mindex] <= a[i] { if a[m] < a[mindex] { mindex := m; } m := m + 1; } a[n], a[mindex] := a[mindex], a[n]; assert forall i,j :: 0 <= i < j < n ==> a[i] <= a[j]; n := n + 1; } } method QuickSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { QuickSortAux(a, 0, a.Length); } twostate predicate SwapFrame(a: array<int>, lo: int, hi: int) requires 0 <= lo <= hi <= a.Length reads a { (forall i :: 0 <= i < lo || hi <= i < a.Length ==> a[i] == old(a[i])) && multiset(a[..]) == old(multiset(a[..])) } method QuickSortAux(a: array<int>, lo: int, hi: int) requires 0 <= lo <= hi <= a.Length requires SplitPoint(a, lo) && SplitPoint(a, hi) modifies a ensures forall i,j :: lo <= i < j < hi ==> a[i] <= a[j] ensures SwapFrame(a, lo, hi) ensures SplitPoint(a, lo) && SplitPoint(a, hi) decreases hi - lo { if 2 <= hi - lo { var p := Partition(a, lo, hi); QuickSortAux(a, lo, p); QuickSortAux(a, p + 1, hi); } } method Partition(a: array<int>, lo: int, hi: int) returns (p: int) requires 0 <= lo < hi <= a.Length requires SplitPoint(a, lo) && SplitPoint(a, hi) modifies a ensures lo <= p < hi ensures forall i :: lo <= i < p ==> a[i] < a[p] ensures forall i :: p <= i < hi ==> a[p] <= a[i] ensures SplitPoint(a, lo) && SplitPoint(a, hi) ensures SwapFrame(a, lo, hi) { var pivot := a[lo]; var m, n := lo + 1, hi; while m < n invariant lo + 1 <= m <= n <= hi invariant a[lo] == pivot invariant forall i :: lo + 1 <= i < m ==> a[i] < pivot invariant forall i :: n <= i < hi ==> pivot <= a[i] invariant SplitPoint(a, lo) && SplitPoint(a, hi) invariant SwapFrame(a, lo, hi) { if a[m] < pivot { m := m + 1; } else { a[m], a[n-1] := a[n-1], a[m]; n := n - 1; } } a[lo], a[m - 1] := a[m - 1], a[lo]; return m - 1; }
predicate SplitPoint(a: array<int>, n: int) reads a requires 0 <= n <= n { forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] } method SelectionSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { var n := 0; while n != a.Length // invariant forall i,j :: 0 <= i < n <= j < a.Length ==> a[i] <= a[j] { var mindex, m := n, n; while m != a.Length { if a[m] < a[mindex] { mindex := m; } m := m + 1; } a[n], a[mindex] := a[mindex], a[n]; n := n + 1; } } method QuickSort(a: array<int>) modifies a ensures forall i,j :: 0 <= i < j < a.Length ==> a[i] <= a[j] ensures multiset(a[..]) == old(multiset(a[..])) { QuickSortAux(a, 0, a.Length); } twostate predicate SwapFrame(a: array<int>, lo: int, hi: int) requires 0 <= lo <= hi <= a.Length reads a { (forall i :: 0 <= i < lo || hi <= i < a.Length ==> a[i] == old(a[i])) && multiset(a[..]) == old(multiset(a[..])) } method QuickSortAux(a: array<int>, lo: int, hi: int) requires 0 <= lo <= hi <= a.Length requires SplitPoint(a, lo) && SplitPoint(a, hi) modifies a ensures forall i,j :: lo <= i < j < hi ==> a[i] <= a[j] ensures SwapFrame(a, lo, hi) ensures SplitPoint(a, lo) && SplitPoint(a, hi) { if 2 <= hi - lo { var p := Partition(a, lo, hi); QuickSortAux(a, lo, p); QuickSortAux(a, p + 1, hi); } } method Partition(a: array<int>, lo: int, hi: int) returns (p: int) requires 0 <= lo < hi <= a.Length requires SplitPoint(a, lo) && SplitPoint(a, hi) modifies a ensures lo <= p < hi ensures forall i :: lo <= i < p ==> a[i] < a[p] ensures forall i :: p <= i < hi ==> a[p] <= a[i] ensures SplitPoint(a, lo) && SplitPoint(a, hi) ensures SwapFrame(a, lo, hi) { var pivot := a[lo]; var m, n := lo + 1, hi; while m < n { if a[m] < pivot { m := m + 1; } else { a[m], a[n-1] := a[n-1], a[m]; n := n - 1; } } a[lo], a[m - 1] := a[m - 1], a[lo]; return m - 1; }
285
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_examples_bubblesort.dfy
//https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny function NChoose2(n: int): int { n * (n - 1) / 2 } // sum of all integers in the range [lo, hi) // (inclusive of lo, exclusive of hi) function SumRange(lo: int, hi: int): int decreases hi - lo { if lo >= hi then 0 else SumRange(lo, hi - 1) + hi - 1 } // dafny proves this automatically by induction lemma SumRangeNChoose2(n: nat) ensures SumRange(0, n) == NChoose2(n) {} // dafny proves this automatically by induction // (given the correct decreases clause) lemma SumRangeUnrollLeft(lo: int, hi: int) decreases hi - lo ensures SumRange(lo, hi) == if lo >= hi then 0 else lo + SumRange(lo + 1, hi) {} method BubbleSort(a: array<int>) returns (n: nat) modifies a ensures n <= NChoose2(a.Length) { // it simplifies the remaining invariants to handle the empty array here if a.Length == 0 { return 0; } var i := a.Length - 1; n := 0; while i > 0 invariant 0 <= i < a.Length invariant n <= SumRange(i+1, a.Length) { var j := 0; while j < i invariant n <= SumRange(i+1, a.Length) + j invariant j <= i { if a[j] > a[j+1] { a[j], a[j+1] := a[j+1], a[j]; n := n + 1; } j := j + 1; } assert n <= SumRange(i, a.Length) by { SumRangeUnrollLeft(i, a.Length); // see lemma below } i := i - 1; } calc <= { n; // less or equal to next line by the loop invariant SumRange(1, a.Length); { SumRangeUnrollLeft(0, a.Length); } SumRange(0, a.Length); { SumRangeNChoose2(a.Length); } // see lemma below NChoose2(a.Length); } }
//https://stackoverflow.com/questions/69364687/how-to-prove-time-complexity-of-bubble-sort-using-dafny function NChoose2(n: int): int { n * (n - 1) / 2 } // sum of all integers in the range [lo, hi) // (inclusive of lo, exclusive of hi) function SumRange(lo: int, hi: int): int { if lo >= hi then 0 else SumRange(lo, hi - 1) + hi - 1 } // dafny proves this automatically by induction lemma SumRangeNChoose2(n: nat) ensures SumRange(0, n) == NChoose2(n) {} // dafny proves this automatically by induction // (given the correct decreases clause) lemma SumRangeUnrollLeft(lo: int, hi: int) ensures SumRange(lo, hi) == if lo >= hi then 0 else lo + SumRange(lo + 1, hi) {} method BubbleSort(a: array<int>) returns (n: nat) modifies a ensures n <= NChoose2(a.Length) { // it simplifies the remaining invariants to handle the empty array here if a.Length == 0 { return 0; } var i := a.Length - 1; n := 0; while i > 0 { var j := 0; while j < i { if a[j] > a[j+1] { a[j], a[j+1] := a[j+1], a[j]; n := n + 1; } j := j + 1; } SumRangeUnrollLeft(i, a.Length); // see lemma below } i := i - 1; } calc <= { n; // less or equal to next line by the loop invariant SumRange(1, a.Length); { SumRangeUnrollLeft(0, a.Length); } SumRange(0, a.Length); { SumRangeNChoose2(a.Length); } // see lemma below NChoose2(a.Length); } }
286
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_examples_relativeOrder.dfy
predicate IsEven (n: int) { n % 2 == 0 } method FindEvenNumbers (arr: array<int>) returns (evenNumbers: array<int>) ensures forall x :: x in arr[..] && IsEven(x) ==> x in evenNumbers[..]; ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..] ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==> exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m] { var evenList: seq<int> := []; ghost var indices: seq<int> := []; for i := 0 to arr.Length invariant 0 <= i <= arr.Length invariant 0 <= |evenList| <= i invariant forall x :: x in arr[..i] && IsEven(x) ==> x in evenList[..] invariant forall x :: x !in arr[..i] ==> x !in evenList invariant |evenList| == |indices| invariant forall k :: 0 <= k < |indices| ==> indices[k] < i invariant forall k, l :: 0 <= k < l < |indices| ==> indices[k] < indices[l] invariant forall k :: 0 <= k < |evenList| ==> 0 <= indices[k] < i <= arr.Length && arr[indices[k]] == evenList[k] invariant forall k, l :: 0 <= k < l < |evenList| ==> exists n, m :: 0 <= n < m < i && evenList[k] == arr[n] && evenList[l] == arr[m] { if IsEven(arr[i]) { evenList := evenList + [arr[i]]; indices := indices + [i]; } } evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]); assert evenList == evenNumbers[..]; }
predicate IsEven (n: int) { n % 2 == 0 } method FindEvenNumbers (arr: array<int>) returns (evenNumbers: array<int>) ensures forall x :: x in arr[..] && IsEven(x) ==> x in evenNumbers[..]; ensures forall x :: x !in arr[..] ==> x !in evenNumbers[..] ensures forall k, l :: 0 <= k < l < evenNumbers.Length ==> exists n, m :: 0 <= n < m < arr.Length && evenNumbers[k] == arr[n] && evenNumbers[l] == arr[m] { var evenList: seq<int> := []; ghost var indices: seq<int> := []; for i := 0 to arr.Length exists n, m :: 0 <= n < m < i && evenList[k] == arr[n] && evenList[l] == arr[m] { if IsEven(arr[i]) { evenList := evenList + [arr[i]]; indices := indices + [i]; } } evenNumbers := new int[|evenList|](i requires 0 <= i < |evenList| => evenList[i]); }
287
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_examples_simpleMultiplication.dfy
method Foo(y: int, x: int) returns (z: int) requires 0 <= y ensures z == x*y { var a: int := 0; z := 0; while a != y invariant 0 <= a <= y invariant z == a*x decreases y-a { z := z + x; a := a + 1; } return z; } function stringToSet(s: string): (r: set<char>) ensures forall x :: 0 <= x < |s| ==> s[x] in r { set x | 0 <= x < |s| :: s[x] } //ensures forall a, b :: 0 <= a < b < |s| ==> forall k, j :: a <=k < j <=b ==> k !=j ==> s[k] != s[j] ==> b-a <= longest // lemma stringSet(s: string) // // { // if |s| != 0 { // } // } method Main() { var sample: string := "test"; var foof := Foo(3,4); var test: set<char> := stringToSet(sample); // var test := set x | 0 <= x < |sample| :: sample[x]; assert test == stringToSet(sample); assert forall x :: 0 <= x < |sample| ==> sample[x] in test; assert 't' in sample; assert 't' in test; print foof; }
method Foo(y: int, x: int) returns (z: int) requires 0 <= y ensures z == x*y { var a: int := 0; z := 0; while a != y { z := z + x; a := a + 1; } return z; } function stringToSet(s: string): (r: set<char>) ensures forall x :: 0 <= x < |s| ==> s[x] in r { set x | 0 <= x < |s| :: s[x] } //ensures forall a, b :: 0 <= a < b < |s| ==> forall k, j :: a <=k < j <=b ==> k !=j ==> s[k] != s[j] ==> b-a <= longest // lemma stringSet(s: string) // // { // if |s| != 0 { // } // } method Main() { var sample: string := "test"; var foof := Foo(3,4); var test: set<char> := stringToSet(sample); // var test := set x | 0 <= x < |sample| :: sample[x]; print foof; }
288
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_heap2.dfy
class Heap { var arr: array<int> constructor Heap (input: array<int>) ensures this.arr == input { this.arr := input; } function parent(idx: int): int { if idx == 0 then -1 else if idx % 2 == 0 then (idx-2)/2 else (idx-1)/2 } predicate IsMaxHeap(input: seq<int>) { forall i :: 0 <= i < |input| ==> && (2*i+1 < |input| ==> input[i] >= input[2*i+1]) && (2*i+2 < |input| ==> input[i] >= input[2*i+2]) } predicate IsAlmostMaxHeap(input: seq<int>, idx: int) requires 0 <= idx { && (forall i :: 0 <= i < |input| ==> && (2*i+1 < |input| && i != idx ==> input[i] >= input[2*i+1]) && (2*i+2 < |input| && i != idx ==> input[i] >= input[2*i+2])) && (0 <= parent(idx) < |input| && 2*idx+1 < |input| ==> input[parent(idx)] >= input[2*idx+1]) && (0 <= parent(idx) < |input| && 2*idx+2 < |input| ==> input[parent(idx)] >= input[2*idx+2]) } method heapify(idx: int) returns (nidx: int) modifies this, this.arr requires 0 <= idx < this.arr.Length requires IsAlmostMaxHeap(this.arr[..], idx) ensures nidx == -1 || idx < nidx < this.arr.Length ensures nidx == -1 ==> IsMaxHeap(this.arr[..]) ensures idx < nidx < this.arr.Length ==> IsAlmostMaxHeap(this.arr[..], nidx) { if (2*idx+1 >= this.arr.Length) && (2*idx+2 >= this.arr.Length) { nidx := -1; assert IsMaxHeap(this.arr[..]); return; } else { assert 2*idx+1 < this.arr.Length || 2*idx+2 < this.arr.Length; nidx := idx; if 2*idx+1 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+1] { nidx := 2*idx+1; } if 2*idx+2 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+2] { nidx := 2*idx+2; } if nidx == idx { nidx := -1; return; } else { assert nidx == 2*idx+1 || nidx == 2*idx+2; this.arr[idx], this.arr[nidx] := this.arr[nidx], this.arr[idx]; forall i | 0 <= i < this.arr.Length ensures (i != nidx) && (2*i+1 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+1]) { if (i != nidx) && (2*i+1 < this.arr.Length) { if 2*i+1 == idx { assert this.arr[i] >= this.arr[2*i+1]; } } } forall i | 0 <= i < this.arr.Length ensures (i != nidx) && (2*i+2 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+2]) { if (i != nidx) && (2*i+2 < this.arr.Length) { if 2*i+2 == idx { assert this.arr[i] >= this.arr[2*i+2]; } } } } } } }
class Heap { var arr: array<int> constructor Heap (input: array<int>) ensures this.arr == input { this.arr := input; } function parent(idx: int): int { if idx == 0 then -1 else if idx % 2 == 0 then (idx-2)/2 else (idx-1)/2 } predicate IsMaxHeap(input: seq<int>) { forall i :: 0 <= i < |input| ==> && (2*i+1 < |input| ==> input[i] >= input[2*i+1]) && (2*i+2 < |input| ==> input[i] >= input[2*i+2]) } predicate IsAlmostMaxHeap(input: seq<int>, idx: int) requires 0 <= idx { && (forall i :: 0 <= i < |input| ==> && (2*i+1 < |input| && i != idx ==> input[i] >= input[2*i+1]) && (2*i+2 < |input| && i != idx ==> input[i] >= input[2*i+2])) && (0 <= parent(idx) < |input| && 2*idx+1 < |input| ==> input[parent(idx)] >= input[2*idx+1]) && (0 <= parent(idx) < |input| && 2*idx+2 < |input| ==> input[parent(idx)] >= input[2*idx+2]) } method heapify(idx: int) returns (nidx: int) modifies this, this.arr requires 0 <= idx < this.arr.Length requires IsAlmostMaxHeap(this.arr[..], idx) ensures nidx == -1 || idx < nidx < this.arr.Length ensures nidx == -1 ==> IsMaxHeap(this.arr[..]) ensures idx < nidx < this.arr.Length ==> IsAlmostMaxHeap(this.arr[..], nidx) { if (2*idx+1 >= this.arr.Length) && (2*idx+2 >= this.arr.Length) { nidx := -1; return; } else { nidx := idx; if 2*idx+1 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+1] { nidx := 2*idx+1; } if 2*idx+2 < this.arr.Length && this.arr[nidx] < this.arr[2*idx+2] { nidx := 2*idx+2; } if nidx == idx { nidx := -1; return; } else { this.arr[idx], this.arr[nidx] := this.arr[nidx], this.arr[idx]; forall i | 0 <= i < this.arr.Length ensures (i != nidx) && (2*i+1 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+1]) { if (i != nidx) && (2*i+1 < this.arr.Length) { if 2*i+1 == idx { } } } forall i | 0 <= i < this.arr.Length ensures (i != nidx) && (2*i+2 < this.arr.Length) ==> (this.arr[i] >= this.arr[2*i+2]) { if (i != nidx) && (2*i+2 < this.arr.Length) { if 2*i+2 == idx { } } } } } } }
289
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_BoatsToSavePeople.dfy
/* function numRescueBoats(people: number[], limit: number): number { //people.sort((a,b) => a-b); binsort(people, limit); let boats = 0; let lower = 0, upper = people.length-1; while(lower <= upper) { if(people[upper] == limit || people[upper]+people[lower] > limit) { boats++ upper--; }else if(people[upper]+people[lower] <= limit) { upper--; lower++; boats++; } } return boats; }; nums[k++] = i+1; function binsort(nums: number[], limit: number) { let result = new Array(limit); result.fill(0); for(let i = 0; i < nums.length; i++) { result[nums[i]-1]++; } var k = 0; for(let i=0; i < result.length; i++) { for(let j = 0; j < result[i]; j++) { nums[k++] = i+1; } } } */ function sumBoat(s: seq<nat>): nat requires 1 <= |s| <= 2 { if |s| == 1 then s[0] else s[0] + s[1] } predicate isSafeBoat(boat: seq<nat>, limit: nat) { 1 <= |boat| <= 2 && sumBoat(boat) <= limit } function multisetAdd(ss: seq<seq<nat>>): multiset<nat> { if ss == [] then multiset{} else multiset(ss[0]) + multisetAdd(ss[1..]) } predicate multisetEqual(ss: seq<seq<nat>>, xs: seq<nat>) { multiset(xs) == multisetAdd(ss) } predicate allSafe(boats: seq<seq<nat>>, limit: nat) { forall boat :: boat in boats ==> isSafeBoat(boat, limit) } predicate sorted(list: seq<int>) { forall i,j :: 0 <= i < j < |list| ==> list[i] <= list[j] } method numRescueBoats(people: seq<nat>, limit: nat) returns (boats: nat) requires |people| >= 1 requires sorted(people) requires forall i: nat :: i < |people| ==> 1 <= people[i] <= limit ensures exists boatConfig: seq<seq<nat>> :: multisetEqual(boatConfig, people) && allSafe(boatConfig, limit) && boats == |boatConfig|// && forall boatConfigs :: multisetEqual(boatConfigs, people) && allSafe(boatConfigs, limit) ==> boats <= |boatConfigs| { boats := 0; var lower: nat := 0; var upper: int := |people| - 1; ghost var visitedUpper: multiset<nat> := multiset{}; ghost var visitedLower: multiset<nat> := multiset{}; ghost var remaining: multiset<nat> := multiset(people); ghost var safeBoats: seq<seq<nat>> := []; while lower <= upper invariant 0 <= lower <= |people| invariant lower-1 <= upper < |people| invariant visitedUpper == multiset(people[upper+1..]) invariant visitedLower == multiset(people[..lower]) invariant allSafe(safeBoats, limit) invariant multisetAdd(safeBoats) == visitedLower + visitedUpper; invariant |safeBoats| == boats { if people[upper] == limit || people[upper] + people[lower] > limit { boats := boats + 1; assert isSafeBoat([people[upper]], limit); safeBoats := [[people[upper]]] + safeBoats; assert visitedUpper == multiset(people[upper+1..]); ghost var gu := people[upper+1..]; assert multiset(gu) == visitedUpper; assert people[upper..] == [people[upper]] + gu; visitedUpper := visitedUpper + multiset{people[upper]}; upper := upper - 1; assert people[(upper+1)..] == [people[upper+1]] + gu; }else{ ghost var gl := people[..lower]; boats := boats + 1; if lower == upper { visitedLower := visitedLower + multiset{people[lower]}; assert isSafeBoat([people[lower]], limit); safeBoats := [[people[lower]]] + safeBoats; }else{ ghost var gu := people[upper+1..]; assert multiset(gu) == visitedUpper; visitedUpper := visitedUpper + multiset{people[upper]}; visitedLower := visitedLower + multiset{people[lower]}; assert isSafeBoat([people[upper], people[lower]], limit); safeBoats := [[people[upper], people[lower]]] + safeBoats; upper := upper - 1; assert people[(upper+1)..] == [people[upper+1]] + gu; } lower := lower + 1; assert people[..lower] == gl + [people[lower-1]]; } } assert visitedLower == multiset(people[..lower]); assert visitedUpper == multiset(people[upper+1..]); assert upper+1 == lower; assert people == people[..lower] + people[upper+1..]; assert visitedLower + visitedUpper == multiset(people); } /* limit 3 [3,2,2,1] lower = 0 upper = 3 upper = 2 lower= 0 lower = 1 upper = 1 lower = 2 [..2] upper = 1 [2..] */
/* function numRescueBoats(people: number[], limit: number): number { //people.sort((a,b) => a-b); binsort(people, limit); let boats = 0; let lower = 0, upper = people.length-1; while(lower <= upper) { if(people[upper] == limit || people[upper]+people[lower] > limit) { boats++ upper--; }else if(people[upper]+people[lower] <= limit) { upper--; lower++; boats++; } } return boats; }; nums[k++] = i+1; function binsort(nums: number[], limit: number) { let result = new Array(limit); result.fill(0); for(let i = 0; i < nums.length; i++) { result[nums[i]-1]++; } var k = 0; for(let i=0; i < result.length; i++) { for(let j = 0; j < result[i]; j++) { nums[k++] = i+1; } } } */ function sumBoat(s: seq<nat>): nat requires 1 <= |s| <= 2 { if |s| == 1 then s[0] else s[0] + s[1] } predicate isSafeBoat(boat: seq<nat>, limit: nat) { 1 <= |boat| <= 2 && sumBoat(boat) <= limit } function multisetAdd(ss: seq<seq<nat>>): multiset<nat> { if ss == [] then multiset{} else multiset(ss[0]) + multisetAdd(ss[1..]) } predicate multisetEqual(ss: seq<seq<nat>>, xs: seq<nat>) { multiset(xs) == multisetAdd(ss) } predicate allSafe(boats: seq<seq<nat>>, limit: nat) { forall boat :: boat in boats ==> isSafeBoat(boat, limit) } predicate sorted(list: seq<int>) { forall i,j :: 0 <= i < j < |list| ==> list[i] <= list[j] } method numRescueBoats(people: seq<nat>, limit: nat) returns (boats: nat) requires |people| >= 1 requires sorted(people) requires forall i: nat :: i < |people| ==> 1 <= people[i] <= limit ensures exists boatConfig: seq<seq<nat>> :: multisetEqual(boatConfig, people) && allSafe(boatConfig, limit) && boats == |boatConfig|// && forall boatConfigs :: multisetEqual(boatConfigs, people) && allSafe(boatConfigs, limit) ==> boats <= |boatConfigs| { boats := 0; var lower: nat := 0; var upper: int := |people| - 1; ghost var visitedUpper: multiset<nat> := multiset{}; ghost var visitedLower: multiset<nat> := multiset{}; ghost var remaining: multiset<nat> := multiset(people); ghost var safeBoats: seq<seq<nat>> := []; while lower <= upper { if people[upper] == limit || people[upper] + people[lower] > limit { boats := boats + 1; safeBoats := [[people[upper]]] + safeBoats; ghost var gu := people[upper+1..]; visitedUpper := visitedUpper + multiset{people[upper]}; upper := upper - 1; }else{ ghost var gl := people[..lower]; boats := boats + 1; if lower == upper { visitedLower := visitedLower + multiset{people[lower]}; safeBoats := [[people[lower]]] + safeBoats; }else{ ghost var gu := people[upper+1..]; visitedUpper := visitedUpper + multiset{people[upper]}; visitedLower := visitedLower + multiset{people[lower]}; safeBoats := [[people[upper], people[lower]]] + safeBoats; upper := upper - 1; } lower := lower + 1; } } } /* limit 3 [3,2,2,1] lower = 0 upper = 3 upper = 2 lower= 0 lower = 1 upper = 1 lower = 2 [..2] upper = 1 [2..] */
290
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_FindPivotIndex.dfy
/* https://leetcode.com/problems/find-pivot-index/description/ Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11 Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. Example 3: Input: nums = [2,1,-1] Output: 0 Explanation: The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums[1] + nums[2] = 1 + -1 = 0 ```TypeScript function pivotIndex(nums: number[]): number { const n = nums.length; let leftsums = [0], rightsums = [0]; for(let i=1; i < n+1; i++) { leftsums.push(nums[i-1]+leftsums[i-1]); rightsums.push(nums[n-i]+rightsums[i-1]); } for(let i=0; i <= n; i++) { if(leftsums[i] == rightsums[n-(i+1)]) return i; } return -1; }; ``` */ function sum(nums: seq<int>): int { // if |nums| == 0 then 0 else nums[0]+sum(nums[1..]) if |nums| == 0 then 0 else sum(nums[0..(|nums|-1)])+nums[|nums|-1] } function sumUp(nums: seq<int>): int { if |nums| == 0 then 0 else nums[0]+sumUp(nums[1..]) } // By Divyanshu Ranjan lemma sumUpLemma(a: seq<int>, b: seq<int>) ensures sumUp(a + b) == sumUp(a) + sumUp(b) { if a == [] { assert a + b == b; } else { sumUpLemma(a[1..], b); calc { sumUp(a + b); { assert (a + b)[0] == a[0]; assert (a + b)[1..] == a[1..] + b; } a[0] + sumUp(a[1..] + b); a[0] + sumUp(a[1..]) + sumUp(b); } } } // By Divyanshu Ranjan lemma sumsEqual(nums: seq<int>) decreases |nums| ensures sum(nums) == sumUp(nums) { if nums == [] {} else { var ln := |nums|-1; calc { sumUp(nums[..]); { assert nums[..] == nums[0..ln] + [nums[ln]]; sumUpLemma(nums[0..ln], [nums[ln]]); } sumUp(nums[0..ln]) + sumUp([nums[ln]]); { assert forall a:: sumUp([a]) == a; } sumUp(nums[0..ln]) + nums[ln]; { sumsEqual(nums[0..ln]); } sum(nums[0..ln]) + nums[ln]; } } } method FindPivotIndex(nums: seq<int>) returns (index: int) requires |nums| > 0 ensures index == -1 ==> forall k: nat :: k < |nums| ==> sum(nums[0..k]) != sum(nums[(k+1)..]) ensures 0 <= index < |nums| ==> sum(nums[0..index]) == sum(nums[(index+1)..]) { var leftsums: seq<int> := [0]; var rightsums: seq<int> := [0]; var i := 1; assert leftsums[0] == sum(nums[0..0]); assert rightsums[0] == sumUp(nums[|nums|..]); while i < |nums|+1 invariant 1 <= i <= |nums|+1 invariant |leftsums| == i invariant |rightsums| == i invariant forall k: nat :: 0 <= k < i && k <= |nums| ==> leftsums[k] == sum(nums[0..k]) invariant forall k: nat :: 0 <= k < i && k <= |nums| ==> rightsums[k] == sumUp(nums[(|nums|-k)..]) { leftsums := leftsums + [leftsums[i-1]+nums[i-1]]; assert nums[0..i] == nums[0..i-1]+[nums[i-1]]; rightsums := rightsums + [nums[|nums|-i]+rightsums[i-1]]; i := i + 1; } assert forall k: nat :: 0 <= k < i && k <= |nums| ==> rightsums[k] == sum(nums[(|nums|-k)..]) by { forall k: nat | 0 <= k < i && k <= |nums| ensures sumUp(nums[(|nums|-k)..]) == sum(nums[(|nums|-k)..]) ensures rightsums[k] == sumUp(nums[(|nums|-k)..]) { sumsEqual(nums[(|nums|-k)..]); } } i :=0; while i < |nums| invariant 0 <= i <= |nums| invariant forall k: nat :: k < i ==> sum(nums[0..k]) != sum(nums[(k+1)..]) { var x := |nums|-(i+1); if leftsums[i] == rightsums[x] { assert sum(nums[0..i]) == sum(nums[(i+1)..]); // assert rightsums[i+1] == sum(nums[(|nums|-(i+1))..]); return i; } assert sum(nums[0..i]) != sum(nums[(i+1)..]); i := i + 1; } return -1; }
/* https://leetcode.com/problems/find-pivot-index/description/ Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. Return the leftmost pivot index. If no such index exists, return -1. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The pivot index is 3. Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 Right sum = nums[4] + nums[5] = 5 + 6 = 11 Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. Example 3: Input: nums = [2,1,-1] Output: 0 Explanation: The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums[1] + nums[2] = 1 + -1 = 0 ```TypeScript function pivotIndex(nums: number[]): number { const n = nums.length; let leftsums = [0], rightsums = [0]; for(let i=1; i < n+1; i++) { leftsums.push(nums[i-1]+leftsums[i-1]); rightsums.push(nums[n-i]+rightsums[i-1]); } for(let i=0; i <= n; i++) { if(leftsums[i] == rightsums[n-(i+1)]) return i; } return -1; }; ``` */ function sum(nums: seq<int>): int { // if |nums| == 0 then 0 else nums[0]+sum(nums[1..]) if |nums| == 0 then 0 else sum(nums[0..(|nums|-1)])+nums[|nums|-1] } function sumUp(nums: seq<int>): int { if |nums| == 0 then 0 else nums[0]+sumUp(nums[1..]) } // By Divyanshu Ranjan lemma sumUpLemma(a: seq<int>, b: seq<int>) ensures sumUp(a + b) == sumUp(a) + sumUp(b) { if a == [] { } else { sumUpLemma(a[1..], b); calc { sumUp(a + b); { } a[0] + sumUp(a[1..] + b); a[0] + sumUp(a[1..]) + sumUp(b); } } } // By Divyanshu Ranjan lemma sumsEqual(nums: seq<int>) ensures sum(nums) == sumUp(nums) { if nums == [] {} else { var ln := |nums|-1; calc { sumUp(nums[..]); { sumUpLemma(nums[0..ln], [nums[ln]]); } sumUp(nums[0..ln]) + sumUp([nums[ln]]); { } sumUp(nums[0..ln]) + nums[ln]; { sumsEqual(nums[0..ln]); } sum(nums[0..ln]) + nums[ln]; } } } method FindPivotIndex(nums: seq<int>) returns (index: int) requires |nums| > 0 ensures index == -1 ==> forall k: nat :: k < |nums| ==> sum(nums[0..k]) != sum(nums[(k+1)..]) ensures 0 <= index < |nums| ==> sum(nums[0..index]) == sum(nums[(index+1)..]) { var leftsums: seq<int> := [0]; var rightsums: seq<int> := [0]; var i := 1; while i < |nums|+1 { leftsums := leftsums + [leftsums[i-1]+nums[i-1]]; rightsums := rightsums + [nums[|nums|-i]+rightsums[i-1]]; i := i + 1; } forall k: nat | 0 <= k < i && k <= |nums| ensures sumUp(nums[(|nums|-k)..]) == sum(nums[(|nums|-k)..]) ensures rightsums[k] == sumUp(nums[(|nums|-k)..]) { sumsEqual(nums[(|nums|-k)..]); } } i :=0; while i < |nums| { var x := |nums|-(i+1); if leftsums[i] == rightsums[x] { // assert rightsums[i+1] == sum(nums[(|nums|-(i+1))..]); return i; } i := i + 1; } return -1; }
291
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_ReverseLinkedList.dfy
/* https://leetcode.com/problems/reverse-linked-list/description/ * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } function reverseList(head: ListNode | null): ListNode | null { if (head == null) return null; let curr = head; let prev = null; while(curr !== null && curr.next !== null) { let next = curr.next; curr.next = prev; prev = curr; curr = next; } curr.next = prev; return curr; }; */ datatype ListNode = Null | Node(val: nat, next: ListNode) function reverse<A>(x: seq<A>): seq<A> { if x == [] then [] else reverse(x[1..])+[x[0]] } function nodeConcat(xs: ListNode, end: ListNode): ListNode { if xs == Null then end else Node(xs.val, nodeConcat(xs.next, end)) } function reverseList(xs: ListNode): ListNode { if xs == Null then Null else nodeConcat(reverseList(xs.next), Node(xs.val, Null)) } lemma ConcatNullIsRightIdentity(xs: ListNode) ensures xs == nodeConcat(xs, Null) { } lemma ConcatNullIsLeftIdentity(xs: ListNode) ensures xs == nodeConcat(Null, xs) { } lemma ConcatExtensionality(xs: ListNode) requires xs != Null ensures nodeConcat(Node(xs.val, Null), xs.next) == xs; { } lemma ConcatAssociative(xs: ListNode, ys: ListNode, zs: ListNode) ensures nodeConcat(nodeConcat(xs, ys), zs) == nodeConcat(xs, nodeConcat(ys, zs)) { } lemma reverseSingleList(xs: ListNode) requires xs != Null; requires xs.next == Null; ensures reverseList(xs) == xs; { } lemma {:verify true} ConcatReverseList(xs:ListNode, ys: ListNode) ensures reverseList(nodeConcat(xs,ys)) == nodeConcat(reverseList(ys), reverseList(xs)) decreases xs; { if xs == Null { calc { reverseList(nodeConcat(xs,ys)); == {ConcatNullIsLeftIdentity(ys);} reverseList(ys); == {ConcatNullIsRightIdentity(reverseList(ys));} nodeConcat(reverseList(ys), Null); nodeConcat(reverseList(ys), xs); nodeConcat(reverseList(ys), reverseList(xs)); } }else{ var x := Node(xs.val, Null); calc { reverseList(nodeConcat(xs, ys)); reverseList(nodeConcat(nodeConcat(x, xs.next), ys)); == {ConcatAssociative(x, xs.next, ys);} reverseList(nodeConcat(x, nodeConcat(xs.next, ys))); nodeConcat(reverseList(nodeConcat(xs.next, ys)), x); == {ConcatReverseList(xs.next, ys);} nodeConcat(nodeConcat(reverseList(ys) , reverseList(xs.next)), x); == {ConcatAssociative(reverseList(ys), reverseList(xs.next), x);} nodeConcat(reverseList(ys) , nodeConcat(reverseList(xs.next), x)); nodeConcat(reverseList(ys) , reverseList(xs)); } } } lemma reverseReverseListIsIdempotent(xs: ListNode) ensures reverseList(reverseList(xs)) == xs { if xs == Null { }else{ var x := Node(xs.val, Null); calc { reverseList(reverseList(xs)); reverseList(reverseList(nodeConcat(x, xs.next))); == {ConcatReverseList(x, xs.next);} reverseList(nodeConcat(reverseList(xs.next), reverseList(x))); reverseList(nodeConcat(reverseList(xs.next), x)); == {ConcatReverseList(reverseList(xs.next),x);} nodeConcat(reverseList(x), reverseList(reverseList(xs.next))); //dafny can figure out the rest from here nodeConcat(x, reverseList(reverseList(xs.next))); nodeConcat(x, xs.next); xs; } } } lemma {:induction false} reversePreservesMultiset<A>(xs: seq<A>) ensures multiset(xs) == multiset(reverse(xs)) { if xs == [] { }else { var x := xs[0]; assert xs == [x] + xs[1..]; assert multiset(xs) == multiset([x]) + multiset(xs[1..]); assert reverse(xs) == reverse(xs[1..])+[x]; reversePreservesMultiset(xs[1..]); assert multiset(xs[1..]) == multiset(reverse(xs[1..])); } } lemma reversePreservesLength<A>(xs: seq<A>) ensures |xs| == |reverse(xs)| { } lemma lastReverseIsFirst<A>(xs: seq<A>) requires |xs| > 0 ensures xs[0] == reverse(xs)[|reverse(xs)|-1] { reversePreservesLength(xs); assert |xs| == |reverse(xs)|; } lemma firstReverseIsLast<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs)[0] == xs[|xs|-1] { } lemma ReverseConcat<T>(xs: seq<T>, ys: seq<T>) ensures reverse(xs + ys) == reverse(ys) + reverse(xs) { // reveal Reverse(); if |xs| == 0 { assert xs + ys == ys; } else { assert xs + ys == [xs[0]] + (xs[1..] + ys); } } lemma reverseRest<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1]) { firstReverseIsLast(xs); assert xs == xs[0..|xs|-1] + [xs[|xs|-1]]; assert reverse(xs)[0] == xs[ |xs| -1]; assert reverse(xs) == [xs[ |xs| -1]] + reverse(xs)[1..]; calc { reverse(xs); reverse(xs[0..|xs|-1] + [xs[|xs|-1]]); == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);} reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]); } } lemma SeqEq<T>(xs: seq<T>, ys: seq<T>) requires |xs| == |ys| requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i] ensures xs == ys { } lemma ReverseIndexAll<T>(xs: seq<T>) ensures |reverse(xs)| == |xs| ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1] { // reveal Reverse(); } lemma ReverseIndex<T>(xs: seq<T>, i: int) requires 0 <= i < |xs| ensures |reverse(xs)| == |xs| ensures reverse(xs)[i] == xs[|xs| - i - 1] { ReverseIndexAll(xs); assert forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]; } lemma ReverseSingle<A>(xs: seq<A>) requires |xs| == 1 ensures reverse(xs) == xs { } lemma reverseReverseIdempotent<A>(xs: seq<A>) ensures reverse(reverse(xs)) == xs { if xs == [] { }else{ calc { reverse(reverse(xs)); reverse(reverse([xs[0]] + xs[1..])); == {ReverseConcat([xs[0]] , xs[1..]);} reverse(reverse(xs[1..]) + reverse([xs[0]])); == {ReverseSingle([xs[0]]);} reverse(reverse(xs[1..]) + [xs[0]]); == {ReverseConcat(reverse(xs[1..]), [xs[0]]);} reverse([xs[0]]) + reverse(reverse(xs[1..])); [xs[0]] + reverse(reverse(xs[1..])); == {reverseReverseIdempotent(xs[1..]);} xs; } } /* Alternatively */ // ReverseIndexAll(reverse(xs)); // ReverseIndexAll(xs); // SeqEq(reverse(reverse(xs)), xs); } // var x := xs[0]; // assert xs == [x] + xs[1..]; // reversePreservesLength(xs); // assert |xs| == |reverse(xs)|; // calc { // x; // reverse(xs)[|xs|-1]; // == {firstReverseIsLast(reverse(xs));} // reverse(reverse(xs))[0]; // } // var y := xs[|xs|-1]; // calc{ // y; // == {firstReverseIsLast(xs);} // reverse(xs)[0]; // } // assert xs == xs[0..|xs|-1] + [y]; // lastReverseIsFirst(xs); // lastReverseIsFirst(reverse(xs)); // assert reverse(reverse(xs))[0] == x; /* /** https://leetcode.com/problems/linked-list-cycle/description/ * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function hasCycle(head: ListNode | null): boolean { let leader = head; let follower = head; while(leader !== null) { leader = leader.next; if(follower && follower.next) { follower = follower.next.next; }else if(follower && follower.next == null){ follower=follower.next; } if(follower == leader && follower != null) return true; } return false; }; */ method test() { var cycle := Node(1, Null); var next := Node(2, cycle); // cycle.next := next; }
/* https://leetcode.com/problems/reverse-linked-list/description/ * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } function reverseList(head: ListNode | null): ListNode | null { if (head == null) return null; let curr = head; let prev = null; while(curr !== null && curr.next !== null) { let next = curr.next; curr.next = prev; prev = curr; curr = next; } curr.next = prev; return curr; }; */ datatype ListNode = Null | Node(val: nat, next: ListNode) function reverse<A>(x: seq<A>): seq<A> { if x == [] then [] else reverse(x[1..])+[x[0]] } function nodeConcat(xs: ListNode, end: ListNode): ListNode { if xs == Null then end else Node(xs.val, nodeConcat(xs.next, end)) } function reverseList(xs: ListNode): ListNode { if xs == Null then Null else nodeConcat(reverseList(xs.next), Node(xs.val, Null)) } lemma ConcatNullIsRightIdentity(xs: ListNode) ensures xs == nodeConcat(xs, Null) { } lemma ConcatNullIsLeftIdentity(xs: ListNode) ensures xs == nodeConcat(Null, xs) { } lemma ConcatExtensionality(xs: ListNode) requires xs != Null ensures nodeConcat(Node(xs.val, Null), xs.next) == xs; { } lemma ConcatAssociative(xs: ListNode, ys: ListNode, zs: ListNode) ensures nodeConcat(nodeConcat(xs, ys), zs) == nodeConcat(xs, nodeConcat(ys, zs)) { } lemma reverseSingleList(xs: ListNode) requires xs != Null; requires xs.next == Null; ensures reverseList(xs) == xs; { } lemma {:verify true} ConcatReverseList(xs:ListNode, ys: ListNode) ensures reverseList(nodeConcat(xs,ys)) == nodeConcat(reverseList(ys), reverseList(xs)) { if xs == Null { calc { reverseList(nodeConcat(xs,ys)); == {ConcatNullIsLeftIdentity(ys);} reverseList(ys); == {ConcatNullIsRightIdentity(reverseList(ys));} nodeConcat(reverseList(ys), Null); nodeConcat(reverseList(ys), xs); nodeConcat(reverseList(ys), reverseList(xs)); } }else{ var x := Node(xs.val, Null); calc { reverseList(nodeConcat(xs, ys)); reverseList(nodeConcat(nodeConcat(x, xs.next), ys)); == {ConcatAssociative(x, xs.next, ys);} reverseList(nodeConcat(x, nodeConcat(xs.next, ys))); nodeConcat(reverseList(nodeConcat(xs.next, ys)), x); == {ConcatReverseList(xs.next, ys);} nodeConcat(nodeConcat(reverseList(ys) , reverseList(xs.next)), x); == {ConcatAssociative(reverseList(ys), reverseList(xs.next), x);} nodeConcat(reverseList(ys) , nodeConcat(reverseList(xs.next), x)); nodeConcat(reverseList(ys) , reverseList(xs)); } } } lemma reverseReverseListIsIdempotent(xs: ListNode) ensures reverseList(reverseList(xs)) == xs { if xs == Null { }else{ var x := Node(xs.val, Null); calc { reverseList(reverseList(xs)); reverseList(reverseList(nodeConcat(x, xs.next))); == {ConcatReverseList(x, xs.next);} reverseList(nodeConcat(reverseList(xs.next), reverseList(x))); reverseList(nodeConcat(reverseList(xs.next), x)); == {ConcatReverseList(reverseList(xs.next),x);} nodeConcat(reverseList(x), reverseList(reverseList(xs.next))); //dafny can figure out the rest from here nodeConcat(x, reverseList(reverseList(xs.next))); nodeConcat(x, xs.next); xs; } } } lemma {:induction false} reversePreservesMultiset<A>(xs: seq<A>) ensures multiset(xs) == multiset(reverse(xs)) { if xs == [] { }else { var x := xs[0]; reversePreservesMultiset(xs[1..]); } } lemma reversePreservesLength<A>(xs: seq<A>) ensures |xs| == |reverse(xs)| { } lemma lastReverseIsFirst<A>(xs: seq<A>) requires |xs| > 0 ensures xs[0] == reverse(xs)[|reverse(xs)|-1] { reversePreservesLength(xs); } lemma firstReverseIsLast<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs)[0] == xs[|xs|-1] { } lemma ReverseConcat<T>(xs: seq<T>, ys: seq<T>) ensures reverse(xs + ys) == reverse(ys) + reverse(xs) { // reveal Reverse(); if |xs| == 0 { } else { } } lemma reverseRest<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1]) { firstReverseIsLast(xs); calc { reverse(xs); reverse(xs[0..|xs|-1] + [xs[|xs|-1]]); == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);} reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]); } } lemma SeqEq<T>(xs: seq<T>, ys: seq<T>) requires |xs| == |ys| requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i] ensures xs == ys { } lemma ReverseIndexAll<T>(xs: seq<T>) ensures |reverse(xs)| == |xs| ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1] { // reveal Reverse(); } lemma ReverseIndex<T>(xs: seq<T>, i: int) requires 0 <= i < |xs| ensures |reverse(xs)| == |xs| ensures reverse(xs)[i] == xs[|xs| - i - 1] { ReverseIndexAll(xs); } lemma ReverseSingle<A>(xs: seq<A>) requires |xs| == 1 ensures reverse(xs) == xs { } lemma reverseReverseIdempotent<A>(xs: seq<A>) ensures reverse(reverse(xs)) == xs { if xs == [] { }else{ calc { reverse(reverse(xs)); reverse(reverse([xs[0]] + xs[1..])); == {ReverseConcat([xs[0]] , xs[1..]);} reverse(reverse(xs[1..]) + reverse([xs[0]])); == {ReverseSingle([xs[0]]);} reverse(reverse(xs[1..]) + [xs[0]]); == {ReverseConcat(reverse(xs[1..]), [xs[0]]);} reverse([xs[0]]) + reverse(reverse(xs[1..])); [xs[0]] + reverse(reverse(xs[1..])); == {reverseReverseIdempotent(xs[1..]);} xs; } } /* Alternatively */ // ReverseIndexAll(reverse(xs)); // ReverseIndexAll(xs); // SeqEq(reverse(reverse(xs)), xs); } // var x := xs[0]; // assert xs == [x] + xs[1..]; // reversePreservesLength(xs); // assert |xs| == |reverse(xs)|; // calc { // x; // reverse(xs)[|xs|-1]; // == {firstReverseIsLast(reverse(xs));} // reverse(reverse(xs))[0]; // } // var y := xs[|xs|-1]; // calc{ // y; // == {firstReverseIsLast(xs);} // reverse(xs)[0]; // } // assert xs == xs[0..|xs|-1] + [y]; // lastReverseIsFirst(xs); // lastReverseIsFirst(reverse(xs)); // assert reverse(reverse(xs))[0] == x; /* /** https://leetcode.com/problems/linked-list-cycle/description/ * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function hasCycle(head: ListNode | null): boolean { let leader = head; let follower = head; while(leader !== null) { leader = leader.next; if(follower && follower.next) { follower = follower.next.next; }else if(follower && follower.next == null){ follower=follower.next; } if(follower == leader && follower != null) return true; } return false; }; */ method test() { var cycle := Node(1, Null); var next := Node(2, cycle); // cycle.next := next; }
292
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_lc-remove-element.dfy
//https://leetcode.com/problems/remove-element/ method removeElement(nums: array<int>, val: int) returns (i: int) ensures forall k :: 0 < k < i < nums.Length ==> nums[k] != val modifies nums { i := 0; var end := nums.Length - 1; while i <= end invariant 0 <= i <= nums.Length invariant end < nums.Length invariant forall k :: 0 <= k < i ==> nums[k] != val { if(nums[i] == val) { if(nums[end] == val) { end := end - 1; }else{ nums[i], nums[end] := nums[end], nums[i]; i := i + 1; end := end - 1; } }else{ i := i + 1; } } } ///compileTarget:js method Main() { var elems := new int[5][1,2,3,4,5]; var res := removeElement(elems, 5); print res, "\n", elems; }
//https://leetcode.com/problems/remove-element/ method removeElement(nums: array<int>, val: int) returns (i: int) ensures forall k :: 0 < k < i < nums.Length ==> nums[k] != val modifies nums { i := 0; var end := nums.Length - 1; while i <= end { if(nums[i] == val) { if(nums[end] == val) { end := end - 1; }else{ nums[i], nums[end] := nums[end], nums[i]; i := i + 1; end := end - 1; } }else{ i := i + 1; } } } ///compileTarget:js method Main() { var elems := new int[5][1,2,3,4,5]; var res := removeElement(elems, 5); print res, "\n", elems; }
293
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_pathSum.dfy
//https://leetcode.com/problems/path-sum /** function hasPathSum(root: TreeNode | null, targetSum: number): boolean { if(root == null) { return false; } if(root.val-targetSum == 0 && root.left == null && root.right == null) { return true; } return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val); }; */ datatype TreeNode = Nil | Cons(val: nat, left: TreeNode, right: TreeNode) function TreeSeq(root: TreeNode): seq<TreeNode> { match root { case Nil => [Nil] case Cons(val, left, right) => [root]+TreeSeq(left)+TreeSeq(right) } } function TreeSet(root: TreeNode): set<TreeNode> { match root { case Nil => {Nil} case Cons(val, left, right) => TreeSet(left)+{root}+TreeSet(right) } } predicate isPath(paths: seq<TreeNode>, root: TreeNode) { if |paths| == 0 then false else match paths[0] { case Nil => false case Cons(val, left, right) => if |paths| == 1 then root == paths[0] else root == paths[0] && (isPath(paths[1..], left) || isPath(paths[1..], right)) } } function pathSum(paths: seq<TreeNode>): nat { if |paths| == 0 then 0 else match paths[0] { case Nil => 0 case Cons(val, left, right) => val + pathSum(paths[1..]) } } method hasPathSum(root: TreeNode, targetSum: int) returns (b: bool) ensures b ==> exists p: seq<TreeNode> :: isPath(p, root) && pathSum(p) == targetSum { if root == Nil { return false; } if(root.val - targetSum == 0 && root.left == Nil && root.right == Nil) { assert isPath([root], root) && pathSum([root]) == targetSum; return true; } var leftPath := hasPathSum(root.left, targetSum-root.val); var rightPath := hasPathSum(root.right, targetSum-root.val); if leftPath { ghost var p: seq<TreeNode> :| isPath(p, root.left) && pathSum(p) == targetSum-root.val; assert isPath([root]+p, root) && pathSum([root]+p) == targetSum; } if rightPath { ghost var p: seq<TreeNode> :| isPath(p, root.right) && pathSum(p) == targetSum-root.val; assert isPath([root]+p, root) && pathSum([root]+p) == targetSum; } return leftPath || rightPath; } method Test() { var c := Cons(3, Nil, Nil); var b := Cons(2, c, Nil); var a := Cons(1, b, Nil); assert isPath([a], a); assert a.left == b; assert isPath([a,b], a); assert isPath([a,b,c], a); }
//https://leetcode.com/problems/path-sum /** function hasPathSum(root: TreeNode | null, targetSum: number): boolean { if(root == null) { return false; } if(root.val-targetSum == 0 && root.left == null && root.right == null) { return true; } return hasPathSum(root.left, targetSum-root.val) || hasPathSum(root.right, targetSum-root.val); }; */ datatype TreeNode = Nil | Cons(val: nat, left: TreeNode, right: TreeNode) function TreeSeq(root: TreeNode): seq<TreeNode> { match root { case Nil => [Nil] case Cons(val, left, right) => [root]+TreeSeq(left)+TreeSeq(right) } } function TreeSet(root: TreeNode): set<TreeNode> { match root { case Nil => {Nil} case Cons(val, left, right) => TreeSet(left)+{root}+TreeSet(right) } } predicate isPath(paths: seq<TreeNode>, root: TreeNode) { if |paths| == 0 then false else match paths[0] { case Nil => false case Cons(val, left, right) => if |paths| == 1 then root == paths[0] else root == paths[0] && (isPath(paths[1..], left) || isPath(paths[1..], right)) } } function pathSum(paths: seq<TreeNode>): nat { if |paths| == 0 then 0 else match paths[0] { case Nil => 0 case Cons(val, left, right) => val + pathSum(paths[1..]) } } method hasPathSum(root: TreeNode, targetSum: int) returns (b: bool) ensures b ==> exists p: seq<TreeNode> :: isPath(p, root) && pathSum(p) == targetSum { if root == Nil { return false; } if(root.val - targetSum == 0 && root.left == Nil && root.right == Nil) { return true; } var leftPath := hasPathSum(root.left, targetSum-root.val); var rightPath := hasPathSum(root.right, targetSum-root.val); if leftPath { ghost var p: seq<TreeNode> :| isPath(p, root.left) && pathSum(p) == targetSum-root.val; } if rightPath { ghost var p: seq<TreeNode> :| isPath(p, root.right) && pathSum(p) == targetSum-root.val; } return leftPath || rightPath; } method Test() { var c := Cons(3, Nil, Nil); var b := Cons(2, c, Nil); var a := Cons(1, b, Nil); }
294
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_stairClimbing.dfy
/* You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? function climbStairs(n: number): number { let steps = new Array(n+1); steps[0] = 0; steps[1] = 1; steps[2] = 2; for(let i = 3; i <= n; i++) { steps[i] = steps[i-1] + steps[i-2]; } return steps[n]; }; */ datatype Steps = One | Two function stepSum(xs: seq<Steps>): nat { if xs == [] then 0 else (match xs[0] { case One => 1 case Two => 2 } + stepSum(xs[1..])) } ghost predicate stepEndsAt(xs: seq<Steps>, n: nat) { stepSum(xs) == n } ghost predicate allEndAtN(ss: set<seq<Steps> >, n: nat) { forall xs :: xs in ss ==> stepEndsAt(xs, n) } lemma stepBaseZero() ensures exists ss: set< seq<Steps> > :: allEndAtN(ss, 0) && |ss| == 0 { assert allEndAtN({[]}, 0); } lemma stepBaseOne() ensures exists ss: set< seq<Steps> > :: allEndAtN(ss, 1) && |ss| == 1 { assert allEndAtN({[One]}, 1); } lemma stepBaseTwo() ensures exists ss: set< seq<Steps> > :: allEndAtN(ss, 2) && |ss| == 2 { assert allEndAtN({[One,One], [Two]}, 2); } ghost function plusOne(x: seq<Steps>): seq<Steps> { [One]+x } ghost function addOne(ss: set<seq<Steps>>): set<seq<Steps>> ensures forall x :: x in ss ==> plusOne(x) in addOne(ss) ensures addOne(ss) == set x | x in ss :: plusOne(x) { set x | x in ss :: plusOne(x) } lemma SeqsNotEqualImplication<T>(xs: seq<T>, ys: seq<T>, someT: T) requires xs != ys ensures (exists i: nat :: i < |xs| && i <|ys| && xs[i] != ys[i]) || |xs| < |ys| || |ys| < |xs| {} lemma UnequalSeqs<T>(xs: seq<T>, ys: seq<T>, someT: T) requires xs != ys ensures [someT]+xs != [someT]+ys { if |xs| < |ys| {} else if |ys| > |xs| {} else if i: nat :| i < |xs| && i <|ys| && xs[i] != ys[i] { assert ([someT]+xs)[i+1] != ([someT]+ys)[i+1]; } } lemma plusOneNotIn(ss: set<seq<Steps>>, x: seq<Steps>) requires x !in ss ensures plusOne(x) !in addOne(ss) { if x == [] { assert [] !in ss; assert [One]+[] !in addOne(ss); } if plusOne(x) in addOne(ss) { forall y | y in ss ensures y != x ensures plusOne(y) in addOne(ss) ensures plusOne(y) != plusOne(x) { UnequalSeqs(x, y, One); assert plusOne(y) != [One]+x; } assert false; } } lemma addOneSize(ss: set<seq<Steps>>) ensures |addOne(ss)| == |ss| { var size := |ss|; if x :| x in ss { assert |ss - {x}| == size - 1; addOneSize(ss - {x}); assert |addOne(ss-{x})| == size - 1; assert addOne(ss) == addOne(ss-{x}) + {[One]+x}; assert x !in ss-{x}; plusOneNotIn(ss-{x}, x); assert plusOne(x) !in addOne(ss-{x}); assert |addOne(ss)| == |addOne(ss-{x})| + |{[One]+x}|; }else{ } } lemma addOneSum(ss: set<seq<Steps>>, sum: nat) requires allEndAtN(ss, sum) ensures allEndAtN(addOne(ss), sum+1) { } lemma endAtNPlus(ss: set<seq<Steps>>, sz: set<seq<Steps>>, sum: nat) requires allEndAtN(ss, sum) requires allEndAtN(sz, sum) ensures allEndAtN(ss+sz, sum) { } ghost function plusTwo(x: seq<Steps>): seq<Steps> { [Two]+x } ghost function addTwo(ss: set<seq<Steps>>): set<seq<Steps>> ensures forall x :: x in ss ==> plusTwo(x) in addTwo(ss) ensures addTwo(ss) == set x | x in ss :: plusTwo(x) { set x | x in ss :: plusTwo(x) } lemma plusTwoNotIn(ss: set<seq<Steps>>, x: seq<Steps>) requires x !in ss ensures plusTwo(x) !in addTwo(ss) { if x == [] { assert [] !in ss; assert [Two]+[] !in addTwo(ss); } if plusTwo(x) in addTwo(ss) { forall y | y in ss ensures y != x ensures plusTwo(y) in addTwo(ss) ensures plusTwo(y) != plusTwo(x) { UnequalSeqs(x, y, Two); assert plusTwo(y) != [Two]+x; } } } lemma addTwoSize(ss: set<seq<Steps>>) ensures |addTwo(ss)| == |ss| { var size := |ss|; if x :| x in ss { // assert |ss - {x}| == size - 1; addTwoSize(ss - {x}); // assert |addTwo(ss-{x})| == size - 1; assert addTwo(ss) == addTwo(ss-{x}) + {[Two]+x}; // assert x !in ss-{x}; plusTwoNotIn(ss-{x}, x); // assert plusTwo(x) !in addTwo(ss-{x}); assert |addTwo(ss)| == |addTwo(ss-{x})| + |{[Two]+x}|; } } lemma addTwoSum(ss: set<seq<Steps>>, sum: nat) requires allEndAtN(ss, sum) ensures allEndAtN(addTwo(ss), sum+2) { } lemma setSizeAddition<T>(sx: set<T>, sy: set<T>, sz: set<T>) requires sx !! sy requires sz == sx + sy ensures |sx + sy| == |sx| + |sy| ensures |sz| == |sx| + |sy| { } lemma stepSetsAdd(i: nat, steps: array<nat>) requires i >= 2 requires steps.Length >= i+1 requires forall k: nat :: k < i ==> exists ss: set< seq<Steps> > :: steps[k] == |ss| && allEndAtN(ss, k) ensures exists sp : set< seq<Steps> > :: |sp| == steps[i-1] + steps[i-2] && allEndAtN(sp, i) { var oneStepBack :| steps[i-1] == |oneStepBack| && allEndAtN(oneStepBack, i-1); var twoStepBack :| steps[i-2] == |twoStepBack| && allEndAtN(twoStepBack, i-2); var stepForward := addOne(oneStepBack); var stepTwoForward := addTwo(twoStepBack); assert forall x :: x in stepForward ==> x[0] == One; // assert stepForward !! stepTwoForward; addOneSize(oneStepBack); addTwoSize(twoStepBack); var sumSet := stepForward + stepTwoForward; // assert |sumSet| == steps[i-1]+steps[i-2]; } method climbStairs(n: nat) returns (count: nat) ensures exists ss: set< seq<Steps> > :: count == |ss| && allEndAtN(ss, n) { var steps := new nat[n+1]; steps[0] := 0; if n > 0 { steps[1] := 1; } if n > 1 { steps[2] := 2; } stepBaseZero(); stepBaseOne(); stepBaseTwo(); if n < 3 { return steps[n]; } assert steps[0] == 0; assert steps[1] == 1; assert steps[2] == 2; assert forall k: nat :: k < 3 ==> exists ss: set< seq<Steps> > :: steps[k] == |ss| && allEndAtN(ss, k); var i := 3; while i <= n invariant 3 <= i <= n+1 invariant forall k: nat :: k < i ==> exists ss: set< seq<Steps> > :: steps[k] == |ss| && allEndAtN(ss, k) { steps[i] := steps[i-1] + steps[i-2]; stepSetsAdd(i, steps); i := i + 1; } return steps[n]; } method Test() { var foo := [One, One, Two]; assert stepSum(foo) == 4; }
/* You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? function climbStairs(n: number): number { let steps = new Array(n+1); steps[0] = 0; steps[1] = 1; steps[2] = 2; for(let i = 3; i <= n; i++) { steps[i] = steps[i-1] + steps[i-2]; } return steps[n]; }; */ datatype Steps = One | Two function stepSum(xs: seq<Steps>): nat { if xs == [] then 0 else (match xs[0] { case One => 1 case Two => 2 } + stepSum(xs[1..])) } ghost predicate stepEndsAt(xs: seq<Steps>, n: nat) { stepSum(xs) == n } ghost predicate allEndAtN(ss: set<seq<Steps> >, n: nat) { forall xs :: xs in ss ==> stepEndsAt(xs, n) } lemma stepBaseZero() ensures exists ss: set< seq<Steps> > :: allEndAtN(ss, 0) && |ss| == 0 { } lemma stepBaseOne() ensures exists ss: set< seq<Steps> > :: allEndAtN(ss, 1) && |ss| == 1 { } lemma stepBaseTwo() ensures exists ss: set< seq<Steps> > :: allEndAtN(ss, 2) && |ss| == 2 { } ghost function plusOne(x: seq<Steps>): seq<Steps> { [One]+x } ghost function addOne(ss: set<seq<Steps>>): set<seq<Steps>> ensures forall x :: x in ss ==> plusOne(x) in addOne(ss) ensures addOne(ss) == set x | x in ss :: plusOne(x) { set x | x in ss :: plusOne(x) } lemma SeqsNotEqualImplication<T>(xs: seq<T>, ys: seq<T>, someT: T) requires xs != ys ensures (exists i: nat :: i < |xs| && i <|ys| && xs[i] != ys[i]) || |xs| < |ys| || |ys| < |xs| {} lemma UnequalSeqs<T>(xs: seq<T>, ys: seq<T>, someT: T) requires xs != ys ensures [someT]+xs != [someT]+ys { if |xs| < |ys| {} else if |ys| > |xs| {} else if i: nat :| i < |xs| && i <|ys| && xs[i] != ys[i] { } } lemma plusOneNotIn(ss: set<seq<Steps>>, x: seq<Steps>) requires x !in ss ensures plusOne(x) !in addOne(ss) { if x == [] { } if plusOne(x) in addOne(ss) { forall y | y in ss ensures y != x ensures plusOne(y) in addOne(ss) ensures plusOne(y) != plusOne(x) { UnequalSeqs(x, y, One); } } } lemma addOneSize(ss: set<seq<Steps>>) ensures |addOne(ss)| == |ss| { var size := |ss|; if x :| x in ss { addOneSize(ss - {x}); plusOneNotIn(ss-{x}, x); }else{ } } lemma addOneSum(ss: set<seq<Steps>>, sum: nat) requires allEndAtN(ss, sum) ensures allEndAtN(addOne(ss), sum+1) { } lemma endAtNPlus(ss: set<seq<Steps>>, sz: set<seq<Steps>>, sum: nat) requires allEndAtN(ss, sum) requires allEndAtN(sz, sum) ensures allEndAtN(ss+sz, sum) { } ghost function plusTwo(x: seq<Steps>): seq<Steps> { [Two]+x } ghost function addTwo(ss: set<seq<Steps>>): set<seq<Steps>> ensures forall x :: x in ss ==> plusTwo(x) in addTwo(ss) ensures addTwo(ss) == set x | x in ss :: plusTwo(x) { set x | x in ss :: plusTwo(x) } lemma plusTwoNotIn(ss: set<seq<Steps>>, x: seq<Steps>) requires x !in ss ensures plusTwo(x) !in addTwo(ss) { if x == [] { } if plusTwo(x) in addTwo(ss) { forall y | y in ss ensures y != x ensures plusTwo(y) in addTwo(ss) ensures plusTwo(y) != plusTwo(x) { UnequalSeqs(x, y, Two); } } } lemma addTwoSize(ss: set<seq<Steps>>) ensures |addTwo(ss)| == |ss| { var size := |ss|; if x :| x in ss { // assert |ss - {x}| == size - 1; addTwoSize(ss - {x}); // assert |addTwo(ss-{x})| == size - 1; // assert x !in ss-{x}; plusTwoNotIn(ss-{x}, x); // assert plusTwo(x) !in addTwo(ss-{x}); } } lemma addTwoSum(ss: set<seq<Steps>>, sum: nat) requires allEndAtN(ss, sum) ensures allEndAtN(addTwo(ss), sum+2) { } lemma setSizeAddition<T>(sx: set<T>, sy: set<T>, sz: set<T>) requires sx !! sy requires sz == sx + sy ensures |sx + sy| == |sx| + |sy| ensures |sz| == |sx| + |sy| { } lemma stepSetsAdd(i: nat, steps: array<nat>) requires i >= 2 requires steps.Length >= i+1 requires forall k: nat :: k < i ==> exists ss: set< seq<Steps> > :: steps[k] == |ss| && allEndAtN(ss, k) ensures exists sp : set< seq<Steps> > :: |sp| == steps[i-1] + steps[i-2] && allEndAtN(sp, i) { var oneStepBack :| steps[i-1] == |oneStepBack| && allEndAtN(oneStepBack, i-1); var twoStepBack :| steps[i-2] == |twoStepBack| && allEndAtN(twoStepBack, i-2); var stepForward := addOne(oneStepBack); var stepTwoForward := addTwo(twoStepBack); // assert stepForward !! stepTwoForward; addOneSize(oneStepBack); addTwoSize(twoStepBack); var sumSet := stepForward + stepTwoForward; // assert |sumSet| == steps[i-1]+steps[i-2]; } method climbStairs(n: nat) returns (count: nat) ensures exists ss: set< seq<Steps> > :: count == |ss| && allEndAtN(ss, n) { var steps := new nat[n+1]; steps[0] := 0; if n > 0 { steps[1] := 1; } if n > 1 { steps[2] := 2; } stepBaseZero(); stepBaseOne(); stepBaseTwo(); if n < 3 { return steps[n]; } var i := 3; while i <= n { steps[i] := steps[i-1] + steps[i-2]; stepSetsAdd(i, steps); i := i + 1; } return steps[n]; } method Test() { var foo := [One, One, Two]; }
295
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_leetcode_validAnagram.dfy
method toMultiset(s: string) returns (mset: multiset<char>) ensures multiset(s) == mset { mset := multiset{}; for i := 0 to |s| invariant mset == multiset(s[0..i]) { assert s == s[0..i] + [s[i]] + s[(i+1)..]; // assert multiset(s) == multiset(s[0..i])+multiset{s[i]}+multiset(s[(i+1)..]); mset := mset + multiset{s[i]}; } assert s == s[0..|s|]; // assert mset == multiset(s[0..|s|]); return mset; } method msetEqual(s: multiset<char>, t: multiset<char>) returns (equal: bool) ensures s == t <==> equal { ghost var sremoved: multiset<char> := multiset{}; var scopy := s; while scopy != multiset{} invariant s - sremoved == scopy invariant sremoved !! scopy invariant sremoved <= s invariant forall x :: x in sremoved ==> x in s && x in t && t[x] == s[x] { var x :| x in scopy; if !(x in t && s[x] == t[x]) { return false; } var removed := multiset{}; // assert removed[x := s[x]] <= s; sremoved := sremoved + removed[x := s[x]]; scopy := scopy - removed[x := s[x]]; } // assert scopy == multiset{}; // assert s - sremoved == scopy; // assert sremoved == s; // assert forall x :: x in sremoved ==> x in s && x in t && t[x] == s[x]; ghost var tremoved: multiset<char> := multiset{}; var tcopy := t; while tcopy != multiset{} invariant t - tremoved == tcopy invariant tremoved !! tcopy invariant tremoved <= t invariant forall x :: x in tremoved ==> x in s && x in t && t[x] == s[x] { var x :| x in tcopy; if !(x in t && s[x] == t[x]) { return false; } var removed := multiset{}; tremoved := tremoved + removed[x := s[x]]; tcopy := tcopy - removed[x := s[x]]; } // assert forall x :: x in tremoved ==> x in s && x in t && t[x] == s[x]; return true; } method isAnagram(s: string, t: string) returns (equal: bool) ensures (multiset(s) == multiset(t)) == equal { var smset := toMultiset(s); var tmset := toMultiset(t); equal := msetEqual(smset, tmset); }
method toMultiset(s: string) returns (mset: multiset<char>) ensures multiset(s) == mset { mset := multiset{}; for i := 0 to |s| { // assert multiset(s) == multiset(s[0..i])+multiset{s[i]}+multiset(s[(i+1)..]); mset := mset + multiset{s[i]}; } // assert mset == multiset(s[0..|s|]); return mset; } method msetEqual(s: multiset<char>, t: multiset<char>) returns (equal: bool) ensures s == t <==> equal { ghost var sremoved: multiset<char> := multiset{}; var scopy := s; while scopy != multiset{} { var x :| x in scopy; if !(x in t && s[x] == t[x]) { return false; } var removed := multiset{}; // assert removed[x := s[x]] <= s; sremoved := sremoved + removed[x := s[x]]; scopy := scopy - removed[x := s[x]]; } // assert scopy == multiset{}; // assert s - sremoved == scopy; // assert sremoved == s; // assert forall x :: x in sremoved ==> x in s && x in t && t[x] == s[x]; ghost var tremoved: multiset<char> := multiset{}; var tcopy := t; while tcopy != multiset{} { var x :| x in tcopy; if !(x in t && s[x] == t[x]) { return false; } var removed := multiset{}; tremoved := tremoved + removed[x := s[x]]; tcopy := tcopy - removed[x := s[x]]; } // assert forall x :: x in tremoved ==> x in s && x in t && t[x] == s[x]; return true; } method isAnagram(s: string, t: string) returns (equal: bool) ensures (multiset(s) == multiset(t)) == equal { var smset := toMultiset(s); var tmset := toMultiset(t); equal := msetEqual(smset, tmset); }
296
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_lib_seq.dfy
module Seq { export reveals * function ToSet<A>(xs: seq<A>): set<A> ensures forall x :: x in ToSet(xs) ==> x in xs ensures forall x :: x !in ToSet(xs) ==> x !in xs { if xs == [] then {} else {xs[0]}+ToSet(xs[1..]) } predicate substring1<A(==)>(sub: seq<A>, super: seq<A>) { exists k :: 0 <= k < |super| && sub <= super[k..] } ghost predicate isSubstringAlt<A(!new)>(sub: seq<A>, super: seq<A>) { |sub| <= |super| && exists xs: seq<A> :: IsSuffix(xs, super) && sub <= xs } predicate isSubstring<A(==)>(sub: seq<A>, super: seq<A>) { |sub| <= |super| && exists k,j :: 0 <= k < j <= |super| && sub == super[k..j] } lemma SliceOfSliceIsSlice<A>(xs: seq<A>, k: int, j: int, s: int, t: int) requires 0 <= k <= j <= |xs| requires 0 <= s <= t <= j-k ensures xs[k..j][s..t] == xs[(k+s)..(k+s+(t-s))] { if j-k == 0 { }else if t-s == 0 { }else if t-s > 0 { SliceOfSliceIsSlice(xs, k, j, s,t-1); assert xs[k..j][s..t] == xs[k..j][s..(t-1)]+[xs[k..j][t-1]]; } } lemma AllSubstringsAreSubstrings<A>(subsub: seq<A>, sub: seq<A>, super: seq<A>) requires isSubstring(sub, super) requires isSubstring(subsub, sub) ensures isSubstring(subsub, super) { assert |sub| <= |super|; assert |subsub| <= |super|; var k,j :| 0 <= k < j <= |super| && sub == super[k..j]; var s,t :| 0 <= s < t <= |sub| && subsub == sub[s..t]; assert t <= (j-k) <= j; //[3,4,5,6,7,8,9,10,11,12,13][2,7] //k,j //[5,6,7,8,9,10][1..3] //s,t //[5,7,8] // var example:= [3,4,5,6,7,8,9,10,11,12,13]; // assert example[2..7] == [5,6,7,8,9]; // assert example[2..7][1..3] == [6,7]; // assert example[3..5] == [6,7]; // assert k+s+(t-s) // assert 2+1+(3-1) == 5; /* assert s[..idx] == [s[0]] + s[1..idx]; assert s[1..idx] == s[1..][..(idx-1)]; assert s[1..][(idx-1)..] == s[idx..]; */ assert super[..j][..t] == super[..(t)]; assert super[k..][s..] == super[(k+s)..]; if t < j { calc { subsub; super[k..j][s..t]; {SliceOfSliceIsSlice(super,k,j,s,t);} super[(k+s)..(k+s+(t-s))]; } } else if t <= j { } // var z,q :| 0 <= z <= q <= |super| && super[z..q] == super[k..j][s..t]; } predicate IsSuffix<T(==)>(xs: seq<T>, ys: seq<T>) { |xs| <= |ys| && xs == ys[|ys| - |xs|..] } predicate IsPrefix<T(==)>(xs: seq<T>, ys: seq<T>) { |xs| <= |ys| && xs == ys[..|xs|] } lemma PrefixRest<T>(xs: seq<T>, ys: seq<T>) requires IsPrefix(xs, ys) ensures exists yss: seq<T> :: ys == xs + yss && |yss| == |ys|-|xs|; { assert ys == ys[..|xs|] + ys[|xs|..]; } lemma IsSuffixReversed<T>(xs: seq<T>, ys: seq<T>) requires IsSuffix(xs, ys) ensures IsPrefix(reverse(xs), reverse(ys)) { ReverseIndexAll(xs); ReverseIndexAll(ys); } lemma IsPrefixReversed<T>(xs: seq<T>, ys: seq<T>) requires IsPrefix(xs, ys) ensures IsSuffix(reverse(xs), reverse(ys)) { ReverseIndexAll(xs); ReverseIndexAll(ys); } lemma IsPrefixReversedAll<T>(xs: seq<T>, ys: seq<T>) requires IsPrefix(reverse(xs), reverse(ys)) ensures IsSuffix(reverse(reverse(xs)), reverse(reverse(ys))) { ReverseIndexAll(xs); ReverseIndexAll(ys); assert |ys| == |reverse(ys)|; assert reverse(xs) == reverse(ys)[..|reverse(xs)|]; assert reverse(xs) == reverse(ys)[..|xs|]; PrefixRest(reverse(xs), reverse(ys)); var yss :| reverse(ys) == reverse(xs) + yss && |yss| == |ys|-|xs|; reverseReverseIdempotent(ys); ReverseConcat(reverse(xs), yss); calc { reverse(reverse(ys)); ys; reverse(reverse(xs) + yss); reverse(yss)+reverse(reverse(xs)); == {reverseReverseIdempotent(xs);} reverse(yss)+xs; } } predicate IsSuffix2<T(==)>(xs: seq<T>, ys: seq<T>) { |xs| <= |ys| && exists K :: 0 <= K <= |ys|-|xs| && ys == ys[0..K] + xs + ys[(K+|xs|)..] } function reverse<A>(x: seq<A>): seq<A> { if x == [] then [] else reverse(x[1..])+[x[0]] } lemma {:induction false} reversePreservesMultiset<A>(xs: seq<A>) ensures multiset(xs) == multiset(reverse(xs)) { if xs == [] { }else { var x := xs[0]; assert xs == [x] + xs[1..]; assert multiset(xs) == multiset([x]) + multiset(xs[1..]); assert reverse(xs) == reverse(xs[1..])+[x]; reversePreservesMultiset(xs[1..]); assert multiset(xs[1..]) == multiset(reverse(xs[1..])); } } lemma reversePreservesLength<A>(xs: seq<A>) ensures |xs| == |reverse(xs)| { } lemma lastReverseIsFirst<A>(xs: seq<A>) requires |xs| > 0 ensures xs[0] == reverse(xs)[|reverse(xs)|-1] { reversePreservesLength(xs); assert |xs| == |reverse(xs)|; } lemma firstReverseIsLast<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs)[0] == xs[|xs|-1] { } lemma ReverseConcat<T>(xs: seq<T>, ys: seq<T>) ensures reverse(xs + ys) == reverse(ys) + reverse(xs) { // reveal Reverse(); if |xs| == 0 { assert xs + ys == ys; } else { assert xs + ys == [xs[0]] + (xs[1..] + ys); } } lemma reverseRest<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1]) { firstReverseIsLast(xs); assert xs == xs[0..|xs|-1] + [xs[|xs|-1]]; assert reverse(xs)[0] == xs[ |xs| -1]; assert reverse(xs) == [xs[ |xs| -1]] + reverse(xs)[1..]; calc { reverse(xs); reverse(xs[0..|xs|-1] + [xs[|xs|-1]]); == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);} reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]); } } lemma ReverseIndexAll<T>(xs: seq<T>) ensures |reverse(xs)| == |xs| ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1] { // reveal Reverse(); } lemma ReverseIndex<T>(xs: seq<T>, i: int) requires 0 <= i < |xs| ensures |reverse(xs)| == |xs| ensures reverse(xs)[i] == xs[|xs| - i - 1] { ReverseIndexAll(xs); assert forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]; } lemma ReverseIndexBack<T>(xs: seq<T>, i: int) requires 0 <= i < |xs| ensures |reverse(xs)| == |xs| ensures reverse(xs)[|xs| - i - 1] == xs[i] { ReverseIndexAll(xs); assert forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1]; } lemma ReverseSingle<A>(xs: seq<A>) requires |xs| == 1 ensures reverse(xs) == xs { } lemma SeqEq<T>(xs: seq<T>, ys: seq<T>) requires |xs| == |ys| requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i] ensures xs == ys { } lemma reverseReverseIdempotent<A>(xs: seq<A>) ensures reverse(reverse(xs)) == xs { if xs == [] { }else{ calc { reverse(reverse(xs)); reverse(reverse([xs[0]] + xs[1..])); == {ReverseConcat([xs[0]] , xs[1..]);} reverse(reverse(xs[1..]) + reverse([xs[0]])); == {ReverseSingle([xs[0]]);} reverse(reverse(xs[1..]) + [xs[0]]); == {ReverseConcat(reverse(xs[1..]), [xs[0]]);} reverse([xs[0]]) + reverse(reverse(xs[1..])); [xs[0]] + reverse(reverse(xs[1..])); == {reverseReverseIdempotent(xs[1..]);} xs; } } /* Alternatively */ // ReverseIndexAll(reverse(xs)); // ReverseIndexAll(xs); // SeqEq(reverse(reverse(xs)), xs); } lemma notInNotEqual<A>(xs: seq<A>, elem: A) requires elem !in xs ensures forall k :: 0 <= k < |xs| ==> xs[k] != elem { } predicate distinct<A(==)>(s: seq<A>) { forall x,y :: x != y && 0 <= x <= y < |s| ==> s[x] != s[y] } lemma distincts<A>(xs: seq<A>, ys: seq<A>) requires distinct(xs) requires distinct(ys) requires forall x :: x in xs ==> x !in ys requires forall y :: y in ys ==> y !in xs ensures distinct(xs+ys) { var len := |xs + ys|; forall x,y | x != y && 0 <= x <= y < |xs+ys| ensures (xs+ys)[x] != (xs+ys)[y] { if 0 <= x < |xs| && 0 <= y < |xs| { assert (xs+ys)[x] != (xs+ys)[y]; }else if |xs| <= x < |xs+ys| && |xs| <= y < |xs+ys| { assert (xs+ys)[x] != (xs+ys)[y]; }else if 0 <= x < |xs| && |xs| <= y < |xs+ys| { notInNotEqual(ys, xs[x]); assert (xs+ys)[x] != (xs+ys)[y]; } } } lemma reverseDistinct<A>(list: seq<A>) requires distinct(list) ensures distinct(reverse(list)) { ReverseIndexAll(list); } lemma distinctSplits<A>(list: seq<A>) requires distinct(list) ensures forall i :: 1 <= i < |list| ==> distinct(list[..i]) {} lemma multisetItems<A>(list: seq<A>, item: A) requires item in list requires multiset(list)[item] > 1 ensures exists i,j :: 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j { var k :| 0 <= k < |list| && list[k] == item; var rest := list[..k]+list[k+1..]; assert list == list[..k]+[item]+list[k+1..]; assert multiset(list) == multiset(list[..k])+multiset(list[k+1..])+multiset{item}; } lemma distinctMultisetIs1<A>(list: seq<A>, item: A) requires distinct(list) requires item in list ensures multiset(list)[item] == 1 { if multiset(list)[item] == 0 { assert false; } if multiset(list)[item] > 1 { multisetItems(list, item); var i,j :| 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j; } } lemma indistinctMultisetIsGreaterThan1<A>(list: seq<A>) requires !distinct(list) ensures exists item :: multiset(list)[item] > 1 { var x,y :| x != y && 0 <= x <= y < |list| && list[x] == list[y]; var item := list[x]; assert x < y; assert list == list[..x] + [item] + list[(x+1)..y] + [item] + list[y+1..]; assert multiset(list)[item] > 1; } lemma multisetIsGreaterThan1Indistinct<A>(list: seq<A>) requires exists item :: multiset(list)[item] > 1 ensures !distinct(list) { var item :| multiset(list)[item] > 1; var x :| 0 <= x < |list| && list[x] == item; assert list == list[..x] + [item] + list[x+1..]; var y :| x != y && 0 <= y < |list| && list[y] == item; } lemma indistinctPlusX<A>(items: seq<A>, x: A) requires !distinct(items) ensures forall i :: 0 <= i < |items| ==> !distinct(items[..i]+[x]+items[i..]) { forall i | 0 <= i < |items| ensures !distinct(items[..i]+[x]+items[i..]) { indistinctMultisetIsGreaterThan1(items); var item :| multiset(items)[item] > 1; var itemsPlus := items[..i]+[x]+items[i..]; assert items == items[..i]+items[i..]; calc { multiset(itemsPlus); multiset(items[..i])+multiset(items[i..])+multiset{x}; multiset(items)+multiset{x}; } assert multiset(itemsPlus)[item] > 1; multisetIsGreaterThan1Indistinct(itemsPlus); } } lemma pigeonHolesMultiset<A>(items: set<A>, list: seq<A>, n: nat) requires |items| == n requires forall x :: x in list ==> x in items requires |list| > n ensures exists item :: multiset(list)[item] > 1 { if x :| multiset(list)[x] > 1 { }else if x :| multiset(list)[x] == 1 { assert x in list; var i :| 0 <= i < |list| && list[i] == x; assert list == list[..i] + [x] + list[i+1..]; assert list == list[..i] + list[i..]; assert multiset(list) == multiset(list[..i])+multiset(list[i+1..])+multiset{x}; var rest := list[..i]+list[i+1..]; assert multiset(rest)[x] == 0; forall y | y in rest ensures y in items-{x} { assert y in items; assert y != x; } if n -1 == 0 { // assert |items| == 1; // assert x in items; assert |items-{x}| == 0; assert list[0] in list; assert list[0] == x; assert list[1] in list; assert list[1] == x; assert false; }else{ pigeonHolesMultiset(items-{x}, rest, n-1); var item :| multiset(rest)[item] > 1; assert multiset(list) == multiset(rest) + multiset{x}; assert multiset(list)[item] > 1; } }else if x :| multiset(list)[x] == 0 {} } lemma pigeonHoles<A>(items: set<A>, list: seq<A>, n: nat) requires |items| == n requires forall x :: x in list ==> x in items requires |list| > n ensures !distinct(list) { if x :| multiset(list)[x] > 1 { multisetItems(list, x); var i,j :| 0 <= i < j < |list| && list[i] == x && list[j] == x && i != j; }else if x :| multiset(list)[x] == 1 { assert x in list; var i :| 0 <= i < |list| && list[i] == x; assert list == list[..i] + [x] + list[i+1..]; assert list == list[..i] + list[i..]; assert multiset(list) == multiset(list[..i])+multiset(list[i+1..])+multiset{x}; assert multiset(list)[x] == 1; var rest := list[..i]+list[i+1..]; assert multiset(rest)[x] == 0; forall y | y in rest ensures y in items-{x} { assert y in items; assert y != x; } pigeonHoles(items-{x}, rest, n-1); assert !distinct(rest); indistinctPlusX(rest, x); assert !distinct(list); }else if x :| multiset(list)[x] == 0 {} } lemma reverseInitList<T>(xs: seq<T>) requires |xs| > 1 requires |reverse(xs)| == |xs| ensures reverse(reverse(xs)[..|xs|-1]) == xs[1..] { assert xs == [xs[0]] + xs[1..]; assert |reverse(xs)| == |xs|; calc { reverse(xs); reverse(xs[1..])+reverse([xs[0]]); reverse(xs[1..])+[xs[0]]; } assert reverse(xs)[..|xs|-1] == reverse(xs[1..]); calc { reverse(reverse(xs)[..|xs|-1]); reverse(reverse(xs[1..])); == {reverseReverseIdempotent(xs[1..]);} xs[1..]; } } method SeqTest() { var t1 := [4,5,6,1,2,3]; // assert t1 == [4,5,6]+[1,2,3]; var s1 := [1,2,3]; assert IsSuffix(s1,t1); // assert isSubstring(s1,t1); assert substring1(s1, t1); } }
module Seq { export reveals * function ToSet<A>(xs: seq<A>): set<A> ensures forall x :: x in ToSet(xs) ==> x in xs ensures forall x :: x !in ToSet(xs) ==> x !in xs { if xs == [] then {} else {xs[0]}+ToSet(xs[1..]) } predicate substring1<A(==)>(sub: seq<A>, super: seq<A>) { exists k :: 0 <= k < |super| && sub <= super[k..] } ghost predicate isSubstringAlt<A(!new)>(sub: seq<A>, super: seq<A>) { |sub| <= |super| && exists xs: seq<A> :: IsSuffix(xs, super) && sub <= xs } predicate isSubstring<A(==)>(sub: seq<A>, super: seq<A>) { |sub| <= |super| && exists k,j :: 0 <= k < j <= |super| && sub == super[k..j] } lemma SliceOfSliceIsSlice<A>(xs: seq<A>, k: int, j: int, s: int, t: int) requires 0 <= k <= j <= |xs| requires 0 <= s <= t <= j-k ensures xs[k..j][s..t] == xs[(k+s)..(k+s+(t-s))] { if j-k == 0 { }else if t-s == 0 { }else if t-s > 0 { SliceOfSliceIsSlice(xs, k, j, s,t-1); } } lemma AllSubstringsAreSubstrings<A>(subsub: seq<A>, sub: seq<A>, super: seq<A>) requires isSubstring(sub, super) requires isSubstring(subsub, sub) ensures isSubstring(subsub, super) { var k,j :| 0 <= k < j <= |super| && sub == super[k..j]; var s,t :| 0 <= s < t <= |sub| && subsub == sub[s..t]; //[3,4,5,6,7,8,9,10,11,12,13][2,7] //k,j //[5,6,7,8,9,10][1..3] //s,t //[5,7,8] // var example:= [3,4,5,6,7,8,9,10,11,12,13]; // assert example[2..7] == [5,6,7,8,9]; // assert example[2..7][1..3] == [6,7]; // assert example[3..5] == [6,7]; // assert k+s+(t-s) // assert 2+1+(3-1) == 5; /* */ if t < j { calc { subsub; super[k..j][s..t]; {SliceOfSliceIsSlice(super,k,j,s,t);} super[(k+s)..(k+s+(t-s))]; } } else if t <= j { } // var z,q :| 0 <= z <= q <= |super| && super[z..q] == super[k..j][s..t]; } predicate IsSuffix<T(==)>(xs: seq<T>, ys: seq<T>) { |xs| <= |ys| && xs == ys[|ys| - |xs|..] } predicate IsPrefix<T(==)>(xs: seq<T>, ys: seq<T>) { |xs| <= |ys| && xs == ys[..|xs|] } lemma PrefixRest<T>(xs: seq<T>, ys: seq<T>) requires IsPrefix(xs, ys) ensures exists yss: seq<T> :: ys == xs + yss && |yss| == |ys|-|xs|; { } lemma IsSuffixReversed<T>(xs: seq<T>, ys: seq<T>) requires IsSuffix(xs, ys) ensures IsPrefix(reverse(xs), reverse(ys)) { ReverseIndexAll(xs); ReverseIndexAll(ys); } lemma IsPrefixReversed<T>(xs: seq<T>, ys: seq<T>) requires IsPrefix(xs, ys) ensures IsSuffix(reverse(xs), reverse(ys)) { ReverseIndexAll(xs); ReverseIndexAll(ys); } lemma IsPrefixReversedAll<T>(xs: seq<T>, ys: seq<T>) requires IsPrefix(reverse(xs), reverse(ys)) ensures IsSuffix(reverse(reverse(xs)), reverse(reverse(ys))) { ReverseIndexAll(xs); ReverseIndexAll(ys); PrefixRest(reverse(xs), reverse(ys)); var yss :| reverse(ys) == reverse(xs) + yss && |yss| == |ys|-|xs|; reverseReverseIdempotent(ys); ReverseConcat(reverse(xs), yss); calc { reverse(reverse(ys)); ys; reverse(reverse(xs) + yss); reverse(yss)+reverse(reverse(xs)); == {reverseReverseIdempotent(xs);} reverse(yss)+xs; } } predicate IsSuffix2<T(==)>(xs: seq<T>, ys: seq<T>) { |xs| <= |ys| && exists K :: 0 <= K <= |ys|-|xs| && ys == ys[0..K] + xs + ys[(K+|xs|)..] } function reverse<A>(x: seq<A>): seq<A> { if x == [] then [] else reverse(x[1..])+[x[0]] } lemma {:induction false} reversePreservesMultiset<A>(xs: seq<A>) ensures multiset(xs) == multiset(reverse(xs)) { if xs == [] { }else { var x := xs[0]; reversePreservesMultiset(xs[1..]); } } lemma reversePreservesLength<A>(xs: seq<A>) ensures |xs| == |reverse(xs)| { } lemma lastReverseIsFirst<A>(xs: seq<A>) requires |xs| > 0 ensures xs[0] == reverse(xs)[|reverse(xs)|-1] { reversePreservesLength(xs); } lemma firstReverseIsLast<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs)[0] == xs[|xs|-1] { } lemma ReverseConcat<T>(xs: seq<T>, ys: seq<T>) ensures reverse(xs + ys) == reverse(ys) + reverse(xs) { // reveal Reverse(); if |xs| == 0 { } else { } } lemma reverseRest<A>(xs: seq<A>) requires |xs| > 0 ensures reverse(xs) == [xs[ |xs| -1 ] ] + reverse(xs[0..|xs|-1]) { firstReverseIsLast(xs); calc { reverse(xs); reverse(xs[0..|xs|-1] + [xs[|xs|-1]]); == {ReverseConcat(xs[0..|xs|-1], [xs[ |xs|-1 ]]);} reverse([xs[ |xs|-1 ]]) + reverse(xs[0..|xs|-1]); } } lemma ReverseIndexAll<T>(xs: seq<T>) ensures |reverse(xs)| == |xs| ensures forall i :: 0 <= i < |xs| ==> reverse(xs)[i] == xs[|xs| - i - 1] { // reveal Reverse(); } lemma ReverseIndex<T>(xs: seq<T>, i: int) requires 0 <= i < |xs| ensures |reverse(xs)| == |xs| ensures reverse(xs)[i] == xs[|xs| - i - 1] { ReverseIndexAll(xs); } lemma ReverseIndexBack<T>(xs: seq<T>, i: int) requires 0 <= i < |xs| ensures |reverse(xs)| == |xs| ensures reverse(xs)[|xs| - i - 1] == xs[i] { ReverseIndexAll(xs); } lemma ReverseSingle<A>(xs: seq<A>) requires |xs| == 1 ensures reverse(xs) == xs { } lemma SeqEq<T>(xs: seq<T>, ys: seq<T>) requires |xs| == |ys| requires forall i :: 0 <= i < |xs| ==> xs[i] == ys[i] ensures xs == ys { } lemma reverseReverseIdempotent<A>(xs: seq<A>) ensures reverse(reverse(xs)) == xs { if xs == [] { }else{ calc { reverse(reverse(xs)); reverse(reverse([xs[0]] + xs[1..])); == {ReverseConcat([xs[0]] , xs[1..]);} reverse(reverse(xs[1..]) + reverse([xs[0]])); == {ReverseSingle([xs[0]]);} reverse(reverse(xs[1..]) + [xs[0]]); == {ReverseConcat(reverse(xs[1..]), [xs[0]]);} reverse([xs[0]]) + reverse(reverse(xs[1..])); [xs[0]] + reverse(reverse(xs[1..])); == {reverseReverseIdempotent(xs[1..]);} xs; } } /* Alternatively */ // ReverseIndexAll(reverse(xs)); // ReverseIndexAll(xs); // SeqEq(reverse(reverse(xs)), xs); } lemma notInNotEqual<A>(xs: seq<A>, elem: A) requires elem !in xs ensures forall k :: 0 <= k < |xs| ==> xs[k] != elem { } predicate distinct<A(==)>(s: seq<A>) { forall x,y :: x != y && 0 <= x <= y < |s| ==> s[x] != s[y] } lemma distincts<A>(xs: seq<A>, ys: seq<A>) requires distinct(xs) requires distinct(ys) requires forall x :: x in xs ==> x !in ys requires forall y :: y in ys ==> y !in xs ensures distinct(xs+ys) { var len := |xs + ys|; forall x,y | x != y && 0 <= x <= y < |xs+ys| ensures (xs+ys)[x] != (xs+ys)[y] { if 0 <= x < |xs| && 0 <= y < |xs| { }else if |xs| <= x < |xs+ys| && |xs| <= y < |xs+ys| { }else if 0 <= x < |xs| && |xs| <= y < |xs+ys| { notInNotEqual(ys, xs[x]); } } } lemma reverseDistinct<A>(list: seq<A>) requires distinct(list) ensures distinct(reverse(list)) { ReverseIndexAll(list); } lemma distinctSplits<A>(list: seq<A>) requires distinct(list) ensures forall i :: 1 <= i < |list| ==> distinct(list[..i]) {} lemma multisetItems<A>(list: seq<A>, item: A) requires item in list requires multiset(list)[item] > 1 ensures exists i,j :: 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j { var k :| 0 <= k < |list| && list[k] == item; var rest := list[..k]+list[k+1..]; } lemma distinctMultisetIs1<A>(list: seq<A>, item: A) requires distinct(list) requires item in list ensures multiset(list)[item] == 1 { if multiset(list)[item] == 0 { } if multiset(list)[item] > 1 { multisetItems(list, item); var i,j :| 0 <= i < j < |list| && list[i] == item && list[j] == item && i != j; } } lemma indistinctMultisetIsGreaterThan1<A>(list: seq<A>) requires !distinct(list) ensures exists item :: multiset(list)[item] > 1 { var x,y :| x != y && 0 <= x <= y < |list| && list[x] == list[y]; var item := list[x]; } lemma multisetIsGreaterThan1Indistinct<A>(list: seq<A>) requires exists item :: multiset(list)[item] > 1 ensures !distinct(list) { var item :| multiset(list)[item] > 1; var x :| 0 <= x < |list| && list[x] == item; var y :| x != y && 0 <= y < |list| && list[y] == item; } lemma indistinctPlusX<A>(items: seq<A>, x: A) requires !distinct(items) ensures forall i :: 0 <= i < |items| ==> !distinct(items[..i]+[x]+items[i..]) { forall i | 0 <= i < |items| ensures !distinct(items[..i]+[x]+items[i..]) { indistinctMultisetIsGreaterThan1(items); var item :| multiset(items)[item] > 1; var itemsPlus := items[..i]+[x]+items[i..]; calc { multiset(itemsPlus); multiset(items[..i])+multiset(items[i..])+multiset{x}; multiset(items)+multiset{x}; } multisetIsGreaterThan1Indistinct(itemsPlus); } } lemma pigeonHolesMultiset<A>(items: set<A>, list: seq<A>, n: nat) requires |items| == n requires forall x :: x in list ==> x in items requires |list| > n ensures exists item :: multiset(list)[item] > 1 { if x :| multiset(list)[x] > 1 { }else if x :| multiset(list)[x] == 1 { var i :| 0 <= i < |list| && list[i] == x; var rest := list[..i]+list[i+1..]; forall y | y in rest ensures y in items-{x} { } if n -1 == 0 { // assert |items| == 1; // assert x in items; }else{ pigeonHolesMultiset(items-{x}, rest, n-1); var item :| multiset(rest)[item] > 1; } }else if x :| multiset(list)[x] == 0 {} } lemma pigeonHoles<A>(items: set<A>, list: seq<A>, n: nat) requires |items| == n requires forall x :: x in list ==> x in items requires |list| > n ensures !distinct(list) { if x :| multiset(list)[x] > 1 { multisetItems(list, x); var i,j :| 0 <= i < j < |list| && list[i] == x && list[j] == x && i != j; }else if x :| multiset(list)[x] == 1 { var i :| 0 <= i < |list| && list[i] == x; var rest := list[..i]+list[i+1..]; forall y | y in rest ensures y in items-{x} { } pigeonHoles(items-{x}, rest, n-1); indistinctPlusX(rest, x); }else if x :| multiset(list)[x] == 0 {} } lemma reverseInitList<T>(xs: seq<T>) requires |xs| > 1 requires |reverse(xs)| == |xs| ensures reverse(reverse(xs)[..|xs|-1]) == xs[1..] { calc { reverse(xs); reverse(xs[1..])+reverse([xs[0]]); reverse(xs[1..])+[xs[0]]; } calc { reverse(reverse(xs)[..|xs|-1]); reverse(reverse(xs[1..])); == {reverseReverseIdempotent(xs[1..]);} xs[1..]; } } method SeqTest() { var t1 := [4,5,6,1,2,3]; // assert t1 == [4,5,6]+[1,2,3]; var s1 := [1,2,3]; // assert isSubstring(s1,t1); } }
297
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_algorithms and leetcode_math_pearson.dfy
function eight(x: nat):nat { 9 * x + 5 } predicate isOdd(x: nat) { x % 2 == 1 } predicate isEven(x: nat) { x % 2 == 0 } lemma eightL(x: nat) requires isOdd(x) ensures isEven(eight(x)) { } function nineteenf(x: nat): nat { 7*x+4 } function nineteens(x: nat): nat { 3*x+11 } lemma nineteenlemma(x: nat) requires isEven(nineteenf(x)) ensures isOdd(nineteens(x)) { } function relationDomain<T>(s: set<(T,T)>): set<T> { set z | z in s :: z.1 } predicate reflexive<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { forall s :: s in S ==> (s,s) in R } predicate symmetric<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { forall x: T, y:T :: x in S && y in S && (x,y) in R ==> (y, x) in R } predicate transitive<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { forall a,b,c :: a in S && b in S && c in S && (a,b) in R && (b,c) in R ==> (a,c) in R } predicate equivalenceRelation<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { reflexive(R, S) && symmetric(R, S) && transitive(R, S) } predicate relationOnASet<T>(R: set<(T,T)>, S: set<T>) { forall ts :: ts in R ==> ts.0 in S && ts.1 in S } // lemma equivUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) // requires |R_1| > 0 // requires |R_2| > 0 // requires |S_1| > 0 // requires |S_2| > 0 // requires relationOnASet(R_1, S_1) // requires relationOnASet(R_2, S_2) // requires equivalenceRelation(R_1, S_1) // requires equivalenceRelation(R_2, S_2) // ensures equivalenceRelation(R_1+R_2, S_1+S_2) // { // reflexiveUnion(R_1, S_1, R_2, S_2); // symmetricUnion(R_1, S_1, R_2, S_2); // transitiveUnion(R_1, S_1, R_2, S_2); // } lemma reflexiveUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) requires |R_1| > 0 requires |R_2| > 0 requires |S_1| > 0 requires |S_2| > 0 requires relationOnASet(R_1, S_1) requires relationOnASet(R_2, S_2) requires reflexive(R_1, S_1) requires reflexive(R_2, S_2) ensures reflexive(R_1+R_2, S_1+S_2) { } lemma symmetricUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) requires |R_1| > 0 requires |R_2| > 0 requires |S_1| > 0 requires |S_2| > 0 requires relationOnASet(R_1, S_1) requires relationOnASet(R_2, S_2) requires symmetric(R_1, S_1) requires symmetric(R_2, S_2) ensures symmetric(R_1+R_2, S_1+S_2) { // assert R_1 <= (R_1+R_2); // assert R_2 <= (R_1+R_2); // assert symmetric(R_1, S_1); // assert symmetric(R_2, S_2); forall x,y | x in S_1+S_2 && y in S_1+S_2 && (x,y) in R_1+R_2 ensures (y,x) in R_1+R_2 { // assert x in S_1+S_2; // assert y in S_1+S_2; // assert (x,y) in R_1+R_2; // calc { // (x,y) in R_1+R_2; // ==> // (x,y) in R_1 || (x,y) in R_2; // } // calc { // x in S_1+S_2; // ==> // x in S_1 || x in S_2; // } // calc { // y in S_1+S_2; // ==> // y in S_1 || y in S_2; // } // assert (x,y) in R_1 ==> x in S_1 && y in S_1; // assert (x,y) in R_2 ==> x in S_2 && y in S_2; // assert (x,y) in R_1 || (x,y) in R_2; if x in S_1 && y in S_1 && (x,y) in R_1 { // assert x in S_1; // assert y in S_1; // assert (x,y) in R_1; // assert (y,x) in R_1; assert (y,x) in R_1+R_2; }else if x in S_2 && y in S_2 && (x,y) in R_2 { // assert x in S_2; // assert y in S_2; // assert (x,y) in R_2; // assert (y,x) in R_2; assert (y,x) in R_1+R_2; } } } lemma transitiveUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) requires |R_1| > 0 requires |R_2| > 0 requires |S_1| > 0 requires |S_2| > 0 requires relationOnASet(R_1, S_1) requires relationOnASet(R_2, S_2) requires transitive(R_1, S_1) requires transitive(R_2, S_2) ensures transitive(R_1+R_2, S_1+S_2) { assert R_1 <= (R_1+R_2); assert R_2 <= (R_1+R_2); assume forall a :: a in S_1+S_2 ==> a !in S_1 || a !in S_2; forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 ensures (a,c) in R_1+R_2 { assert a in S_1 ==> b !in S_2; if a in S_1 && b in S_1 && c in S_1 && (a,b) in R_1 && (b,c) in R_1 { assert (a,c) in R_1; assert (a,c) in R_1+R_2; }else if a in S_2 && b in S_2 && c in S_2 && (a,b) in R_2 && (b,c) in R_2 { assert (a,c) in R_2; assert (a,c) in R_1+R_2; } } } // lemma transitiveUnionContra<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) // requires |R_1| > 0 // requires |R_2| > 0 // requires |S_1| > 0 // requires |S_2| > 0 // requires relationOnASet(R_1, S_1) // requires relationOnASet(R_2, S_2) // requires transitive(R_1, S_1) // requires transitive(R_2, S_2) // ensures exists (R_1+R_2, S_1+S_2) :: !transitive(R_1+R_2, S_1+S_2) // { // assume S_1 * S_2 != {}; // if transitive(R_1 + R_2, S_1+S_2) { // forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 // ensures (a,c) in R_1+R_2 // { // if a in S_1 && a !in S_2 && b in S_1 && b in S_2 && c in S_2 && c !in S_1 { // assert (a,c) !in R_1; // assert (a,c) !in R_2; // assert (a,c) !in R_1+R_2; // assert false; // } // } // } // } lemma transitiveUnionContra<T>() returns ( R1: set<(T, T)>, S1: set<T>, R2: set<(T, T)>, S2: set<T>) ensures relationOnASet(R1, S1) ensures relationOnASet(R2, S2) ensures transitive(R1, S1) ensures transitive(R2, S2) ensures ! transitive(R1 + R2, S1 + S2) { var a : T :| assume true; var b : T :| assume a != b; var c : T :| assume a != c && b != c; S1 := {a, b}; S2 := {b, c}; R1 := {(a, b)}; R2 := {(b, c)}; } lemma notTrueAlways<T>() ensures ! (forall S1 : set<T>, S2 : set<T>, R1 : set<(T,T)>, R2 : set<(T, T)> :: relationOnASet(R1, S1) && relationOnASet(R2, S2) && transitive(R1, S1) && transitive(R2, S2) ==> transitive(R1 + R2, S1 + S2) ) { var a, b, c, d := transitiveUnionContra<T>(); } method test() { var x := 7; // assert isEven(eight(7)); var four := 4; // var test := set x: nat,y: nat | 1 <= x <= y <= 5 :: (x,y); var sample := {1,2,3,4,5,6}; var test := set x,y | x in sample && y in sample :: (x,y); var modulos := set x,y | x in sample && y in sample && x % y == 0 :: (x,y); // assert reflexive(test, set x | 1 <=x <= 5); assert reflexive(test, sample); assert symmetric(test, sample); assert transitive(test, sample); assert equivalenceRelation(test, sample); // assert equivalenceRelation(modulos, sample); var hmm := (1,2,3); assert hmm.2 == 3; assert (1,2) in test; // assert 0 <= four < 100 && isEven(nineteenf(four)); ghost var y: nat :| isEven(nineteenf(y)); assert isOdd(nineteens(y)); }
function eight(x: nat):nat { 9 * x + 5 } predicate isOdd(x: nat) { x % 2 == 1 } predicate isEven(x: nat) { x % 2 == 0 } lemma eightL(x: nat) requires isOdd(x) ensures isEven(eight(x)) { } function nineteenf(x: nat): nat { 7*x+4 } function nineteens(x: nat): nat { 3*x+11 } lemma nineteenlemma(x: nat) requires isEven(nineteenf(x)) ensures isOdd(nineteens(x)) { } function relationDomain<T>(s: set<(T,T)>): set<T> { set z | z in s :: z.1 } predicate reflexive<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { forall s :: s in S ==> (s,s) in R } predicate symmetric<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { forall x: T, y:T :: x in S && y in S && (x,y) in R ==> (y, x) in R } predicate transitive<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { forall a,b,c :: a in S && b in S && c in S && (a,b) in R && (b,c) in R ==> (a,c) in R } predicate equivalenceRelation<T>(R: set<(T,T)>, S: set<T>) requires relationOnASet(R, S) { reflexive(R, S) && symmetric(R, S) && transitive(R, S) } predicate relationOnASet<T>(R: set<(T,T)>, S: set<T>) { forall ts :: ts in R ==> ts.0 in S && ts.1 in S } // lemma equivUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) // requires |R_1| > 0 // requires |R_2| > 0 // requires |S_1| > 0 // requires |S_2| > 0 // requires relationOnASet(R_1, S_1) // requires relationOnASet(R_2, S_2) // requires equivalenceRelation(R_1, S_1) // requires equivalenceRelation(R_2, S_2) // ensures equivalenceRelation(R_1+R_2, S_1+S_2) // { // reflexiveUnion(R_1, S_1, R_2, S_2); // symmetricUnion(R_1, S_1, R_2, S_2); // transitiveUnion(R_1, S_1, R_2, S_2); // } lemma reflexiveUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) requires |R_1| > 0 requires |R_2| > 0 requires |S_1| > 0 requires |S_2| > 0 requires relationOnASet(R_1, S_1) requires relationOnASet(R_2, S_2) requires reflexive(R_1, S_1) requires reflexive(R_2, S_2) ensures reflexive(R_1+R_2, S_1+S_2) { } lemma symmetricUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) requires |R_1| > 0 requires |R_2| > 0 requires |S_1| > 0 requires |S_2| > 0 requires relationOnASet(R_1, S_1) requires relationOnASet(R_2, S_2) requires symmetric(R_1, S_1) requires symmetric(R_2, S_2) ensures symmetric(R_1+R_2, S_1+S_2) { // assert R_1 <= (R_1+R_2); // assert R_2 <= (R_1+R_2); // assert symmetric(R_1, S_1); // assert symmetric(R_2, S_2); forall x,y | x in S_1+S_2 && y in S_1+S_2 && (x,y) in R_1+R_2 ensures (y,x) in R_1+R_2 { // assert x in S_1+S_2; // assert y in S_1+S_2; // assert (x,y) in R_1+R_2; // calc { // (x,y) in R_1+R_2; // ==> // (x,y) in R_1 || (x,y) in R_2; // } // calc { // x in S_1+S_2; // ==> // x in S_1 || x in S_2; // } // calc { // y in S_1+S_2; // ==> // y in S_1 || y in S_2; // } // assert (x,y) in R_1 ==> x in S_1 && y in S_1; // assert (x,y) in R_2 ==> x in S_2 && y in S_2; // assert (x,y) in R_1 || (x,y) in R_2; if x in S_1 && y in S_1 && (x,y) in R_1 { // assert x in S_1; // assert y in S_1; // assert (x,y) in R_1; // assert (y,x) in R_1; }else if x in S_2 && y in S_2 && (x,y) in R_2 { // assert x in S_2; // assert y in S_2; // assert (x,y) in R_2; // assert (y,x) in R_2; } } } lemma transitiveUnion<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) requires |R_1| > 0 requires |R_2| > 0 requires |S_1| > 0 requires |S_2| > 0 requires relationOnASet(R_1, S_1) requires relationOnASet(R_2, S_2) requires transitive(R_1, S_1) requires transitive(R_2, S_2) ensures transitive(R_1+R_2, S_1+S_2) { assume forall a :: a in S_1+S_2 ==> a !in S_1 || a !in S_2; forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 ensures (a,c) in R_1+R_2 { if a in S_1 && b in S_1 && c in S_1 && (a,b) in R_1 && (b,c) in R_1 { }else if a in S_2 && b in S_2 && c in S_2 && (a,b) in R_2 && (b,c) in R_2 { } } } // lemma transitiveUnionContra<T>(R_1: set<(T,T)>, S_1: set<T>, R_2: set<(T,T)>, S_2: set<T>) // requires |R_1| > 0 // requires |R_2| > 0 // requires |S_1| > 0 // requires |S_2| > 0 // requires relationOnASet(R_1, S_1) // requires relationOnASet(R_2, S_2) // requires transitive(R_1, S_1) // requires transitive(R_2, S_2) // ensures exists (R_1+R_2, S_1+S_2) :: !transitive(R_1+R_2, S_1+S_2) // { // assume S_1 * S_2 != {}; // if transitive(R_1 + R_2, S_1+S_2) { // forall a,b,c | a in S_1+S_2 && b in S_1+S_2 && c in S_1+S_2 && (a,b) in R_1+R_2 && (b,c) in R_1+R_2 // ensures (a,c) in R_1+R_2 // { // if a in S_1 && a !in S_2 && b in S_1 && b in S_2 && c in S_2 && c !in S_1 { // assert (a,c) !in R_1; // assert (a,c) !in R_2; // assert (a,c) !in R_1+R_2; // assert false; // } // } // } // } lemma transitiveUnionContra<T>() returns ( R1: set<(T, T)>, S1: set<T>, R2: set<(T, T)>, S2: set<T>) ensures relationOnASet(R1, S1) ensures relationOnASet(R2, S2) ensures transitive(R1, S1) ensures transitive(R2, S2) ensures ! transitive(R1 + R2, S1 + S2) { var a : T :| assume true; var b : T :| assume a != b; var c : T :| assume a != c && b != c; S1 := {a, b}; S2 := {b, c}; R1 := {(a, b)}; R2 := {(b, c)}; } lemma notTrueAlways<T>() ensures ! (forall S1 : set<T>, S2 : set<T>, R1 : set<(T,T)>, R2 : set<(T, T)> :: relationOnASet(R1, S1) && relationOnASet(R2, S2) && transitive(R1, S1) && transitive(R2, S2) ==> transitive(R1 + R2, S1 + S2) ) { var a, b, c, d := transitiveUnionContra<T>(); } method test() { var x := 7; // assert isEven(eight(7)); var four := 4; // var test := set x: nat,y: nat | 1 <= x <= y <= 5 :: (x,y); var sample := {1,2,3,4,5,6}; var test := set x,y | x in sample && y in sample :: (x,y); var modulos := set x,y | x in sample && y in sample && x % y == 0 :: (x,y); // assert reflexive(test, set x | 1 <=x <= 5); // assert equivalenceRelation(modulos, sample); var hmm := (1,2,3); // assert 0 <= four < 100 && isEven(nineteenf(four)); ghost var y: nat :| isEven(nineteenf(y)); }
298
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_BubbleSort.dfy
predicate sorted(a:array<int>, from:int, to:int) requires a != null; reads a; requires 0 <= from <= to <= a.Length; { forall u, v :: from <= u < v < to ==> a[u] <= a[v] } predicate pivot(a:array<int>, to:int, pvt:int) requires a != null; reads a; requires 0 <= pvt < to <= a.Length; { forall u, v :: 0 <= u < pvt < v < to ==> a[u] <= a[v] } method bubbleSort (a: array<int>) requires a != null && a.Length > 0; modifies a; ensures sorted(a, 0, a.Length); ensures multiset(a[..]) == multiset(old(a[..])); { var i:nat := 1; while (i < a.Length) invariant i <= a.Length; invariant sorted(a, 0, i); invariant multiset(a[..]) == multiset(old(a[..])); { var j:nat := i; while (j > 0) invariant multiset(a[..]) == multiset(old(a[..])); invariant sorted(a, 0, j); invariant sorted(a, j, i+1); invariant pivot(a, i+1, j); { if (a[j-1] > a[j]) { var temp:int := a[j-1]; a[j-1] := a[j]; a[j] := temp; } j := j - 1; } i := i+1; } }
predicate sorted(a:array<int>, from:int, to:int) requires a != null; reads a; requires 0 <= from <= to <= a.Length; { forall u, v :: from <= u < v < to ==> a[u] <= a[v] } predicate pivot(a:array<int>, to:int, pvt:int) requires a != null; reads a; requires 0 <= pvt < to <= a.Length; { forall u, v :: 0 <= u < pvt < v < to ==> a[u] <= a[v] } method bubbleSort (a: array<int>) requires a != null && a.Length > 0; modifies a; ensures sorted(a, 0, a.Length); ensures multiset(a[..]) == multiset(old(a[..])); { var i:nat := 1; while (i < a.Length) { var j:nat := i; while (j > 0) { if (a[j-1] > a[j]) { var temp:int := a[j-1]; a[j-1] := a[j]; a[j] := temp; } j := j - 1; } i := i+1; } }
299
Program-Verification-Dataset_tmp_tmpgbdrlnu__Dafny_basic examples_BubbleSort_sol.dfy
predicate sorted_between (a:array<int>, from:nat, to:nat) reads a; requires a != null; requires from <= to; requires to <= a.Length; { forall i,j :: from <= i < j < to && 0 <= i < j < a.Length ==> a[i] <= a[j] } predicate sorted (a:array<int>) reads a; requires a!=null; { sorted_between (a, 0, a.Length) } method bubbleSort (a: array<int>) modifies a; requires a != null; requires a.Length > 0; ensures sorted(a); ensures multiset(old(a[..])) == multiset(a[..]); { var i:nat := 1; while (i < a.Length) invariant i <= a.Length; invariant sorted_between (a, 0, i); invariant multiset(old (a[..])) == multiset(a[..]); { var j:nat := i; while (j > 0) invariant 0 <= j <= i; invariant sorted_between (a, 0, j); invariant forall u,v:: 0 <= u < j < v < i+1 ==> a[u] <= a[v]; invariant sorted_between (a, j, i+1); invariant multiset(old (a[..])) == multiset(a[..]); { if (a[j-1] > a[j]) { var temp:int := a[j-1]; // Introduced bug for permutation a[j-1] := a[j]; //a[j-1] := a[j-1]; a[j] := temp; } j := j - 1; } i := i+1; } }
predicate sorted_between (a:array<int>, from:nat, to:nat) reads a; requires a != null; requires from <= to; requires to <= a.Length; { forall i,j :: from <= i < j < to && 0 <= i < j < a.Length ==> a[i] <= a[j] } predicate sorted (a:array<int>) reads a; requires a!=null; { sorted_between (a, 0, a.Length) } method bubbleSort (a: array<int>) modifies a; requires a != null; requires a.Length > 0; ensures sorted(a); ensures multiset(old(a[..])) == multiset(a[..]); { var i:nat := 1; while (i < a.Length) { var j:nat := i; while (j > 0) { if (a[j-1] > a[j]) { var temp:int := a[j-1]; // Introduced bug for permutation a[j-1] := a[j]; //a[j-1] := a[j-1]; a[j] := temp; } j := j - 1; } i := i+1; } }