summaryrefslogtreecommitdiff
path: root/Chalice/tests/refinements/Calculator.chalice
blob: 57c4c87d38c0f87e5a94f8902ee090994820e96f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
  Carrol Morgan's calculator  
  7/2/2010 Kuat Dafny version
  8/22/2010 translated into Chalice
*/ 

class Calc0 {  
  var vals: seq<int>;
  
  method reset() 
    requires acc(vals);
    ensures acc(vals);
  {
    vals := [];
  }
  
  method add(x: int) 
    requires acc(vals);
    ensures acc(vals);
  {
    vals := [x] ++ vals;    
  }
  
  method mean() returns (m: int)     
    requires acc(vals) && |vals| > 0;
    ensures acc(vals);
  {
    m := total(vals)/|vals|;
  }

  unlimited function total(s: seq<int>): int
  {
    |s| == 0 ? 0 : s[0] + total(s[1..])
  }  
}



class Calc1 refines Calc0 {  
  var sum: int;
  var num: int;
  replaces vals by acc(sum) && acc(num) && sum == total(vals) && num == |vals|;

  refines reset()   
  {
    sum := 0;
    num := 0;
  }

  refines add(x: int)    
  {
    sum := sum + x;
    num := num + 1;
  }

  refines mean() returns (m: int)  
  {
    m := sum/num;
  }
}