CS1950Y Lecture #3 Code
1/28/2019
method e1(x: int) returns (r: int)
requires x==5
ensures x==5
{
return x;
}
method e2(x: int) returns (r: int)
requires x < 0 // "weakest" precondition. could also say x < -100
ensures r < 7
{
return x + 7;
}
method e3(x: int) returns (r: int)
requires true
ensures r >= 0
{
if x < 0 { return -x; }
else { return x; }
}
method e4(x: int) returns (r: int)
requires false // no input will work!
ensures r < 0
{
if x < 0 { return -x; }
else { return x; }
}
method e5(x: int) returns (r: int)
requires x > 7 || x < -7
ensures r > 7
{
if x < 0 { return -x; }
else { return x; }
}
method e6(b: bool, x: int) returns (r: int)
//requires x>=1 // this *works*, but is too strong a precondition to fully capture the contract
//requires x>=1 || !b // weaker
requires x != 0 || !b // weaker still
ensures r >= 0
{
if b { return x*x - 1; }
else { return x*x; }
}
method Main() {
print "testing...\n";
var b := binsearch([100,200,300,400], 500);
print b,"\n";
b := binsearch([100,200,300,400], 100);
print b,"\n";
}
// think of this as a "helper function" for writing preconditions (not code! really 2 languages!)
predicate sorted(list: seq)
{
forall i,j :: 0 <= i < j < |list| ==> list[i] <= list[j]
}
method binsearch(s: seq, t: int) returns (r: bool)
requires sorted(s)
ensures r <==> t in s
{
print "calling binsearch for ",s,"\n";
if(|s| < 1) { return false; }
if(|s| == 1) { return s[0] == t; }
var med := |s|/2;
if (s[med] == t) { return true; }
else if(s[med] < t) { r := binsearch(s[med+1..], t); }
else { r := binsearch(s[..med], t); }
}
// think of this as a "helper function" for writing preconditions
// (not code! really 2 languages...)
predicate sorted(s: seq)
{
forall i,j :: 0 <= i < j < |s| ==> s[i] <= s[j]
}