Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tchajed
Created October 15, 2019 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tchajed/1a90aa2a3079e7d07dc356b7b4c0ad8c to your computer and use it in GitHub Desktop.
Save tchajed/1a90aa2a3079e7d07dc356b7b4c0ad8c to your computer and use it in GitHub Desktop.
Iterating over sequences and sets in Dafny
method sum_seq(xs: seq<int>) returns (z:int) {
var sum := 0;
var i := 0;
while i < |xs|
invariant i <= |xs|
{
sum := sum + xs[i];
i := i + 1;
}
return sum;
}
// inspired by https://stackoverflow.com/q/48739486
method sum_set(xs: set<int>) returns (z:int) {
var sum := 0;
var c := xs;
while c != {}
decreases c
invariant c <= xs;
{
var x :| x in c;
sum := sum + x;
c := c - {x};
}
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment