为什么在 Dafny 函数中使用 new 会出错?

Why does using new in a Dafny function give an error?

我想知道为什么我收到以下程序的错误消息:

class KV 
{
  var key : int;
  var value : int;
  constructor (k: int, v: int) modifies this
  {
    this.key := k;
    this.value := v;
  }
}

function foo () : KV
{
   new KV(0,0)
}

我得到了:invalid UnaryExpression当我运行这个。

在 Dafny functions 是纯粹的。它们可以依赖于堆,通过提供 reads 子句。但它们不能有副作用——它们不能修改堆。由于您的函数 foo 有零个参数且没有 reads 子句,因此每次调用时它必须 return 相同的值。内存分配运算符 new 每次调用时都会给出不同的值,因此不能在函数中使用。

同样重要的是要注意 Dafny 函数默认为 ghost。它们在运行时不可执行。相反,它们在编译的验证阶段使用。如果你想要一个非幽灵函数,你必须写 function method 而不是 function

您可以在 method 中使用 new。方法是命令式过程,不需要是纯粹的。

class KV 
{
  var key : int;
  var value : int;
  constructor (k: int, v: int) modifies this
  {
    this.key := k;
    this.value := v;
  }
}

method foo () returns (kv:KV)
{
   kv := new KV(0,0);
}