我试图编写一个简单验证的substring方法实现。 我的方法接受2个字符串并检查str2是否在str1中。 我试图弄清楚为什么我的入侵者没有坚持--Dafny标志着不变量可能不会进入,而我的前/后条件失败。 我对入侵者的看法是有三个主要场景: 1.循环无法在索引i处找到子字符串,并且还有更多要探索的索引 2.循环无法在索引i处找到子字符串 - 不再需要探索索引 3.循环在索引i处找到了子串
代码:
method Main() {
var str1,str2 := "Dafny","fn";
var found,offset := FindSubstring(str1,str2);
assert found by
{
calc {
str2 <= str1[2..];
==>
IsSubsequenceAtOffset(str1,str2,2);
==>
IsSubsequence(str1,str2);
==
found;
}
}
assert offset == 2 by
{
assert found && str2 <= str1[2..];
assert offset != 0 by { assert 'D' == str1[0] != str2[0] == 'f'; }
assert offset != 1 by { assert 'a' == str1[1] != str2[0] == 'f'; }
assert offset != 3 by { assert 'n' == str1[3] != str2[0] == 'f'; }
assert !(offset >= 4) by { assert 4 + |str2| > |str1|; }
}
print "The sequence ";
print str2;
print " is a subsequence of ";
print str1;
print " starting at element ";
print offset;
}
predicate IsSubsequence<T>(q1: seq<T>, q2: seq<T>)
{
exists offset: nat :: offset + |q2| <= |q1| && IsSubsequenceAtOffset(q1,q2,offset)
}
predicate IsSubsequenceAtOffset<T>(q1: seq<T>, q2: seq<T>, offset: nat)
{
offset + |q2| <= |q1| && q2 <= q1[offset..]
}
predicate Inv<T>(str1: seq<T>, str2: seq<T>, offset: nat, found: bool)
{
|str1| > 0 && |str2| > 0 && |str1| >= |str2| && offset <= |str1|-|str2| &&
(!found && offset < |str1|-|str2| ==> !(str2 <= str1[offset..])) &&
(!found && offset == |str1| -|str2| ==> !IsSubsequence(str1, str2)) &&
(found ==> IsSubsequenceAtOffset(str1, str2, offset))
}
method FindSubstring(str1: string, str2: string) returns (found: bool, offset: nat)
requires |str2| <= |str1|
ensures found <==> IsSubsequence(str1,str2)
ensures found ==> IsSubsequenceAtOffset(str1,str2,offset)
{
found, offset := str2 <= str1[0..], 0;
assert Inv(str1,str2,offset,found);
while !found && offset <= (|str1| - |str2|)
invariant Inv(str1,str2,offset,found)
{
if str2 <= str1[(offset + 1)..] {
found, offset := true, offset + 1;
} else {
offset := offset + 1;
}
}
Lemma(str1,str2,found,offset);
}
lemma Lemma(str1: string, str2: string, found: bool, offset: nat)
requires !(!found && offset <= (|str1| - |str2|))
requires Inv(str1,str2,offset,found)
ensures found <==> IsSubsequence(str1,str2)
ensures found ==> IsSubsequenceAtOffset(str1,str2,offset)
{}
链接:http://rise4fun.com/Dafny/QaAbU 任何帮助,将不胜感激。
答案 0 :(得分:2)
http://rise4fun.com/Dafny/q9BG
1} =SUMIFS(OFFSET($C$2:$C$7,0,MATCH($D11,$C$1:$L$1,0)-1),$A$2:$A$7,$B11,$B$2:$B$7,E$10)
中|str1| > 0 && |str2| > 0
失败,因为此条件未添加到函数inv
2)因为FindSubstring
中的循环体检查FindSubstring
的子字符串,所以while循环只需运行offset+1
,因为如果offset < (|str1| - |str2|)
那么就没有offset == (|str1| - |str2|)
。 t存在任何满足str2 <= str1[offset..]
3)在inv
中添加了量词,确保对于k
所有0 <= k <= offset
的偏移,k
str2 <= str1[offset..]
inv
inv
}
调试可能有用的失败不变量的小建议:将{{1}}调用替换为{{1}}的实际主体,dafny将查明不变量中的失败条件。
希望这是有道理的。