我正在尝试在 Alloy 中构造一个递归函数。根据丹尼尔·杰克逊书中显示的语法,这是可能的。我的职能是:
fun auxiliaryToAvoidCyclicRecursion[idTarget:MethodId, m:Method]: Method{
(m.b.id = idTarget) => {
m
} else (m.b.id != idTarget) => {
(m.b = LiteralValue) => {
m
} else {
some mRet:Method, c:Class | mRet in c.methods && m.b.id = mRet.id => auxiliaryToAvoidCyclicRecursion[idTarget, mRet]
}
}
}
Run Code Online (Sandbox Code Playgroud)
但求解器声称该调用auxiliaryToAvoidCyclicRecursion[idTarget, mRet]是这样的:
"This must be a formula expression.
Instead, it has the following possible type(s):
{this/Method}"
Run Code Online (Sandbox Code Playgroud)
问题正是错误消息所说的:auxiliaryToAvoidCyclicRecursion函数的返回类型是Method,您试图在布尔蕴涵中使用它,其中需要公式(即布尔类型的东西)。在任何其他静态类型语言中您都会遇到同样类型的错误。
您可以将函数重写为谓词来解决此问题:
pred auxiliaryToAvoidCyclicRecursion[idTarget:MethodId, m:Method, ans: Method] {
(m.b.id = idTarget) => {
ans = m
} else (m.b.id != idTarget) => {
(m.b = LiteralValue) => {
ans = m
} else {
some mRet:Method, c:Class {
(mRet in c.methods && m.b.id = mRet.id) =>
auxiliaryToAvoidCyclicRecursion[idTarget, mRet, ans]
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不会给您带来编译错误,但要运行它,请确保启用递归(选项 -> 递归深度)。正如您将看到的,最大递归深度为 3,这意味着合金分析器最多可以展开递归调用 3 次,无论分析范围如何。当这还不够时,您仍然可以选择重写模型,以便将相关递归谓词建模为关系。这是一个简单的例子来说明这一点。
具有用于计算列表长度的递归定义函数的链表:
sig Node {
next: lone Node
} {
this !in this.^@next
}
fun len[n: Node]: Int {
(no n.next) => 1 else plus[1, len[n.next]]
}
// instance found when recursion depth is set to 3
run { some n: Node | len[n] > 3 } for 5 but 4 Int
// can't find an instance because of too few recursion unrollings (3),
// despite the scope being big enough
run { some n: Node | len[n] > 4 } for 5 but 4 Int
Run Code Online (Sandbox Code Playgroud)
现在,同一个列表len被建模为关系(即 中的字段Node)
sig Node {
next: lone Node,
len: one Int
} {
this !in this.^@next
(no this.@next) => this.@len = 1 else this.@len = plus[next.@len, 1]
}
// instance found
run { some n: Node | n.len > 4 } for 5 but 4 Int
Run Code Online (Sandbox Code Playgroud)
请注意,后一种方法不使用递归(因此不依赖于“递归深度”配置选项的值),可能(通常是)比前一种方法慢得多。