在Dafny中如何获取有限映射(finite map)的域?
Great question! Let's break this down clearly for you:
Can you get the domain of a given finite map in Dafny?
Absolutely! Dafny does support accessing the domain of a finite map (the set of all keys present in the map), though the syntax might not be exactly what you initially looked for.
How to compute the domain of a finite map m
Dafny doesn't have a built-in m.Domain property or dom(m) function out of the box (which is probably why you didn't spot it in the reference manual), but you have two straightforward ways to get the domain:
Use a set comprehension directly: You can construct the domain set inline using the expression
{ x | x in m }. This iterates over all keys present inmand collects them into a set.
Example:method TestMapDomain() { var m := map[1: "a", 2: "b", 3: "c"]; var domain := { x | x in m }; assert domain == {1, 2, 3}; }Define your own reusable
domfunction: If you prefer a cleanerdom(m)syntax (similar to what you mentioned), you can easily create a helper function to encapsulate the set comprehension:function dom<K, V>(m: map<K, V>): set<K> { { x | x in m } } method TestCustomDom() { var m := map["foo": 42, "bar": 99]; var domain := dom(m); assert domain == {"foo", "bar"}; }
This approach gives you the exact syntax you were hoping for, and it's fully compatible with Dafny's verification capabilities.
内容的提问来源于stack exchange,提问作者Kevin S

