问题
I'm having a problem with creating an array of objects of a class type I created in dafny. The problem is when initialising a new array of that type I'm getting this error in vscode:
unless an initializer is provided for the array elements, a new array of 'Cup' must have empty size
This is the code (actually a stripped back version that still illustrates the problem):
datatype Drink = WATER | LEMONADE | COFFEE | TEA
class Cup {
var volume: int
var drink_type: Drink
var dirty: bool
predicate Valid()
reads this;
{
volume >= 0
}
constructor (v: int, dt: Drink, d: bool)
requires v >= 0;
ensures Valid();
{
volume := v;
drink_type := dt;
dirty := d;
}
}
method FilterCupDrinkType(a: array<Cup>, dt: Drink) returns (b: array<Cup>, n: int)
{
var temp := new Cup[a.Length];
}
I looked through the manual and online but couldn't really find an answer so I'm hoping someone here knows what to do. If its not possible to do this in dafny(very new to dafny) I would appreciate any suggestions on verifying something like this. Thanks!
回答1:
You could create a default Cup
and then initialize the array with it as follows
method FilterCupDrinkType(a: array<Cup>, dt: Drink) returns (b: array<Cup>, n: int)
{
var default := new Cup(0, WATER, false);
var temp := new Cup[a.Length](_ => default);
}
or you could allow temp
to be an array of nullable Cup
s (i.e., Cup?
)
method FilterCupDrinkType(a: array<Cup>, dt: Drink) returns (b: array<Cup>, n: int)
{
var temp := new Cup?[a.Length];
}
or you can copy a
as follows
method FilterCupDrinkType(a: array<Cup>, dt: Drink) returns (b: array<Cup>, n: int)
{
var temp := new Cup[a.Length](i requires 0 <= i < a.Length reads a => a[i]);
}
Often a good way to find solutions for such questions, if you don't want to wait for an answer here, is to search through Dafny's extensive test suite at https://github.com/dafny-lang/dafny/tree/master/Test. Of course the tutorial is a better choice if treats the topic.
来源:https://stackoverflow.com/questions/58788627/creating-an-array-of-a-class-type-in-dafny