|
| 1 | +// RUN: %dafny /compile:3 /rprint:"%t.rprint" /autoTriggers:1 "%s" > "%t" |
| 2 | +// RUN: %diff "%s.expect" "%t" |
| 3 | +// The usual recursive method for computing McCarthy's 91 function |
| 4 | + |
| 5 | +method Main() { |
| 6 | + var s := [3, 99, 100, 101, 1013]; |
| 7 | + |
| 8 | + var n := 0; |
| 9 | + while n < |s| { |
| 10 | + var m := M(s[n]); |
| 11 | + print "M(", s[n], ") = ", m, "\n"; |
| 12 | + n := n + 1; |
| 13 | + } |
| 14 | + |
| 15 | + n := 0; |
| 16 | + while n < |s| { |
| 17 | + print "mc91(", s[n], ") = ", mc91(s[n]), "\n"; |
| 18 | + n := n + 1; |
| 19 | + } |
| 20 | + |
| 21 | + n := 0; |
| 22 | + while n < |s| { |
| 23 | + var m := Mc91(s[n]); |
| 24 | + print "Mc91(", s[n], ") = ", m, "\n"; |
| 25 | + n := n + 1; |
| 26 | + } |
| 27 | + |
| 28 | + n := 0; |
| 29 | + while n < 5 { |
| 30 | + var m := iter(n, mc91, 40); |
| 31 | + print "iter(", n, ", mc91, 40) = ", m, "\n"; |
| 32 | + n := n + 1; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +method M(n: int) returns (r: int) |
| 37 | + ensures r == if n <= 100 then 91 else n - 10 |
| 38 | + decreases 100 - n |
| 39 | +{ |
| 40 | + if n <= 100 { |
| 41 | + r := M(n + 11); |
| 42 | + r := M(r); |
| 43 | + } else { |
| 44 | + r := n - 10; |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// Same as above, but as a function |
| 49 | + |
| 50 | +function method mc91(n: int): int |
| 51 | + ensures n <= 100 ==> mc91(n) == 91 |
| 52 | + decreases 100 - n |
| 53 | +{ |
| 54 | + if n <= 100 then |
| 55 | + mc91(mc91(n + 11)) |
| 56 | + else |
| 57 | + n - 10 |
| 58 | +} |
| 59 | + |
| 60 | +// Iterating a function f e times starting from n |
| 61 | + |
| 62 | +function method iter(e: nat, f: int -> int, n: int): int |
| 63 | + requires forall x :: f.requires(x) && f.reads(x) == {} |
| 64 | +{ |
| 65 | + if e == 0 then n else iter(e-1, f, f(n)) |
| 66 | +} |
| 67 | + |
| 68 | +// Iterative version of McCarthy's 91 function, following in lockstep |
| 69 | +// what the recursive version would do |
| 70 | + |
| 71 | +method Mc91(n0: int) returns (r: int) |
| 72 | + ensures r == mc91(n0) |
| 73 | +{ |
| 74 | + var e, n := 1, n0; |
| 75 | + while e > 0 |
| 76 | + invariant iter(e, mc91, n) == mc91(n0) |
| 77 | + decreases 100 - n + 10 * e, e |
| 78 | + { |
| 79 | + if n <= 100 { |
| 80 | + e, n := e+1, n+11; |
| 81 | + } else { |
| 82 | + e, n := e-1, n-10; |
| 83 | + } |
| 84 | + } |
| 85 | + return n; |
| 86 | +} |
0 commit comments