Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over the elements of a finite set object in Dafny?

Tags:

iterator

dafny

What is the best way to iterate over the elements of a finite set object in Dafny? An example of working code would be delightful.

like image 566
Kevin S Avatar asked Oct 21 '25 15:10

Kevin S


1 Answers

This answer explains how to do it using a while loop, rather than by defining an iterator. The trick is to use the "assign such that" operator, :|, to obtain a value y such that that y is in the set, and then repeat on that set with the y removing, continuing until there are not more elements. The decreases clause is necessary here. With it, Dafny proves termination of the while loop, but without it, not.

method Main()
{
    var x: set<int> := {1, 2, 3};
    var c := x;
    while ( c != {} )
        decreases c;
    {
        var y :| y in c;
        print y, ", ";
        c := c - { y };
    }
}
like image 101
Kevin S Avatar answered Oct 26 '25 19:10

Kevin S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!