I am new to Dafny and am trying to write a simple linked list implementation that adds all the integers stored in a linked list. Here is the code:
class Node {
var elem: int;
var next: Node?;
constructor (data: int)
{
elem := data;
next := null;
}
method addLinkedList() returns (res: int)
{
res := 0;
var current := this;
while(current != null)
{
res := res + current.elem;
current := current.next;
}
}
}
I have a simple node class and I am adding the integers up and moving the pointer to the next node. To me it is obvious that on a real linked list this will terminate as we will eventually reach a node which is null, however I do not know how to prove this to Dafny. When I worked with arrays there was always an obvious decreases clause I could add to a while loop, but I am lost as to what decreases here. I have tried writing a length function as:
function length(node:Node?):int
{
if(node == null) then 0
else 1 + length(node.next)
}
However Dafny warns me that it cannot prove the termination of that either so I cannot use it as a decreases clause on my while loop.
I have tried searching elsewhere but not found anything to remedy this, so any help will be very appreciated, thank you.