统计Z3量化公式中的变量个数

Counting number of variables in Z3 quantified formula

我正在尝试收集公式中的所有变量(Z3py 中的量化公式)。一个小例子

w, x, y, z = Bools('w x y z')
fml = And( ForAll(x, ForAll(y, And(x, y))), ForAll(z, ForAll(w, And(z, w))) ) 

varSet = traverse( fml )

我用来遍历的代码是

def traverse(e):
  r = set()
  def collect(e):
    if is_quantifier(e):
      # Lets assume there is only one type of quantifier
      if e.is_forall():
          collect(e.body())
    else:
      if ( is_and(e) ):
          n = e.num_args()
          for i in range(n):
              collect( e.arg(i) )
      if ( is_or(e) ):
          n = e.num_args()
          for i in range(n):
              collect( e.arg(i) )
      if ( is_not(e) ):
          collect( e.arg(0) )
      if ( is_var(e) ):
          r.add( e )
  collect(e)
  return r

我得到:set([Var(0), Var(1)])。据我了解,这是由于 Z3 使用 De Bruijn index。是否可以避免这种情况并获得所需的集合:set( [Var(0), Var(1), Var(2), Var(3)] )

您的代码是正确的;此示例中没有 Var(2)Var(3)。有两个顶级量词,每个量词的de-Bruijn索引都是0和1。这两个量词不会出现在另一个量词的主体中,所以不会混淆。