这是课程的一部分。这个类被称为 BAG[G -> {HASHABLE, COMPARABLE}] 它继承自 ADT_BAG,ADT_BAG 具有延迟功能,例如计数、扩展、删除、remove_all、add_all...更多,以及要重新实现的域。
域返回 ARRAY[G],它是 G 的排序数组列表
我总是得到后置条件违规“value_semantics”,这与对象比较有关,但我检查过,没有用于对象比较的代码,这很奇怪。
我多次尝试重新制作域功能的代码,但它总是以违反后置条件或失败而告终。
当我检查调试器时,从域返回的数组“a”总是计数为 0,但这没有意义,因为我将键从表移动到“a”但计数仍然为 0。
也许我将错误的键转移到数组?
代码:
count: INTEGER
-- cardinality of the domain
do
result := domain.count -- has to be domain.count because loop invariant: consistent: count = domain.count
end
domain: ARRAY[G]
-- sorted domain of bag
local
tmp: G
a: ARRAY[G]
do
create a.make_empty
across 1 |..| (a.count) as i -- MOVING keys from table to array
loop
across table as t
loop
if not a.has (t.key) then
a.enter (t.key, i.item)
i.forth
end
end
end
across 1 |..| (a.count-1) as i -- SORTING
loop
if a[i.item] > a[i.item+1] then
tmp := a[i.item]
a[i.item] := a[i.item+1]
a[i.item+1] := tmp
end
end
Result := a
ensure then
value_semantics: Result.object_comparison -- VIOLATION THROWN HERE
correct_items: across 1 |..| Result.count as j all
has(Result[j.item]) end
sorted: across 1 |..| (Result.count-1) as j all
Result[j.item] <= Result[j.item+1] end
end
测试代码:
t3: BOOLEAN
local
sorted_domain: ARRAY[STRING]
do
comment("t3:test sorted domain")
sorted_domain := <<"bolts", "hammers", "nuts">>
sorted_domain.compare_objects
Result := bag2.domain ~ sorted_domain -- fails here
check Result end
end