【问题标题】:High order Count(P) in DafnyDafny 中的高阶计数 (P)
【发布时间】:2021-05-25 23:59:17
【问题描述】:

我想在数组上使用高阶 Count(P) 函数,例如:

Count(even, a),或Count(higher_than_10, a),其中第一个参数是谓词,第二个参数是数组。

也就是说,计算这个 P 命题在一个数组上出现了多少次。

Dafny 有办法做到这一点吗?我认为这种函数是存在的,但可能它们的语法已经改变了。

谢谢

我已经看过了:

-https://stackoverflow.com/questions/35167124/dafny-and-counting-of-occurrences
-https://stackoverflow.com/questions/51379857/polymorphism-in-dafny
-https://gitter.im/dafny-lang/community?at=5d90c402086a72719e848f24
-https://www.imperial.ac.uk/events/104961/higher-order-functions-in-the-verification-aware-programming-language-dafny-k-rustan-m-leino/

【问题讨论】:

  • 它不是内置的,所以你必须自己定义它。你问怎么定义?

标签: arrays count predicate higher-order-functions dafny


【解决方案1】:

这是定义此类函数的一种方法。

function method CountHelper<T>(P: T -> bool, a: array<T>, i: int): int
  requires 0 <= i <= a.Length
  reads a
  decreases a.Length - i
{
  if i == a.Length
  then 0
  else (if P(a[i]) then 1 else 0) + CountHelper(P, a, i+1)
}

function method Count<T>(P: T -> bool, a: array<T>): int
  reads a
{
  CountHelper(P, a, 0)
}

method Main()
{
  var a := new int[10] (i => i);
  var evens := Count(x => x % 2 == 0, a);
  print evens, "\n";
  var bigs := Count(x => x >= 5, a);
  print bigs, "\n";
}

运行时,它会按预期打印两次5

$ dafny /compile:3 count.dfy
Dafny 3.0.0.20820

Dafny program verifier finished with 3 verified, 0 errors
Running...

5
5

【讨论】:

  • 这正是我想要的,我真的很感激!一个问题,为什么没有在 Dafny 中集成所有这些有用的和其他语言中的原始函数?
  • 我不会在其他语言中将这些操作称为“原始”。通常,它们位于这些语言的标准库中。大致来说,Dafny 没有标准库,这有点可惜。不确定我对“为什么?”有很好的回答。
  • 我同意,我的意思是标准库。我很好奇,因为很多函数都是众所周知的,并且总是在 Dafny 课程中学习(例如阶乘、斐波那契......),但没有集成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多