【发布时间】:2021-07-20 06:58:35
【问题描述】:
最近我正在学习 SMT 求解器。虽然 SMT 求解器对我来说是一个新概念,但它让我想起了逻辑编程,例如Prolog 和 minikanren。所以我尝试了一个 SMT 求解器中逻辑编程的经典示例。
示例是appendo 关系,我们可以反向执行它。给定一个输出列表,返回所有可能的两个输入,当连接这两个输入列表时返回输出列表。
下面是appendo关系,我在z3/smt2 solver中实现的:
(define-fun-rec appendo ((l (List Int)) (s (List Int))) (List Int)
(ite (= nil l)
s
(insert (head l) (appendo (tail l) s))
))
(declare-const a (List Int))
(declare-const b (List Int))
(assert (= (appendo a b) (insert 1 (insert 2 nil))))
(check-sat)
(get-model)
(echo "solution 1:")
(eval a)
(eval b)
;; nil
;; (insert 1 (insert 2 nil))
(assert (not (= a nil)))
(assert (not (= b (insert 1 (insert 2 nil)))))
(check-sat)
(get-model)
(echo "solution 2:")
(eval a)
(eval b)
;; (insert 1 nil)
;; (insert 2 nil)
(assert (not (= a (insert 1 nil))))
(assert (not (= b (insert 2 nil))))
(check-sat)
(get-model)
(echo "solution 3:")
(eval a)
(eval b)
;; (insert 1 (insert 2 nil))
;; nil
(assert (not (= a (insert 1 (insert 2 nil)))))
(assert (not (= b nil)))
(check-sat)
;; unsat
虽然可行,但这种实现的缺点是它不能自动获得所有令人满意的模型。
根据this的问题,在纯smt2(?)中自动获得所有令人满意的模型似乎是不可能的。我们必须使用一些 API 绑定。
我尝试了几个小时的 z3 python API,但失败了。
有人可以帮我把上面的 smt2 代码转换成 z3py 吗? (z3py 的文档非常简短且难以阅读,尤其是关于如何定义递归函数,请见谅……)
非常感谢。
以下是我未完成的代码:
from z3 import *
## Define List
def DeclareList(sort):
List = Datatype('List_of_%s' % sort.name())
List.declare('cons', ('car', sort), ('cdr', List))
List.declare('nil')
return List.create()
IntList = DeclareList(IntSort())
## Define Rec Function
appendo = RecFunction('appendo', IntList, IntList, IntList)
RecAddDefinition(appendo, [l, s], If(IntList.nil == l, s, IntList.cons(IntList.car(l), appendo(IntList.cdr(l), s)))) ## <== NameError: name 'l' is not defined
a = Const('a', IntList)
b = Const('b', IntList)
## ...
【问题讨论】:
标签: python z3 smt z3py logic-programming