You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dafny中编写简洁的非空集合最小值函数?附代码求助

Clean Implementation of a Minimum Function for Non-Empty Sets in Dafny

Great question! Your initial recursive approach is solid, but we can simplify it significantly by leveraging Dafny's built-in utilities and reducing redundant assertions that the verifier can infer automatically. Here are two streamlined versions:

1. Simplified Recursive Version

This keeps your core recursive logic but cuts down on boilerplate and unnecessary assertions:

method minimum(s: set<int>) returns (out: int)
  requires |s| >= 1
  ensures forall t: int :: t in s ==> out <= t
{
  var y :| y in s;
  out := if |s| > 1 then min(y, minimum(s - {y})) else y;
}

Key Improvements:

  • Replaced the manual conditional check for y < m with Dafny's built-in min function for integers, making the code more readable.
  • Removed redundant assertions like assert |s| == 1 or assert s - {y} == {}—Dafny's verifier can automatically deduce these facts from the precondition and branch condition.
  • Collapsed the if-else block into a single expression for conciseness.

2. Ultra-Concise Selection Expression Version

If you want to skip explicit recursion entirely, Dafny supports direct selection of the minimum element using a choice expression, which aligns with the mathematical definition of a set's minimum:

method minimum(s: set<int>) returns (out: int)
  requires |s| >= 1
  ensures forall t: int :: t in s ==> out <= t
{
  out :| out in s && forall t: int :: t in s ==> out <= t;
}

How This Works:

  • The :| operator tells Dafny to select an element out from the set that satisfies the following predicate: out is in s, and every element in s is greater than or equal to out.
  • The precondition |s| >= 1 guarantees that such an element exists, so the choice is valid.
  • This version is extremely compact and directly mirrors the formal specification of the minimum value.

Both implementations will pass Dafny's verification, with the second option being the most concise while still being fully verifiable.

内容的提问来源于stack exchange,提问作者smithjonesjr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:31:59