2

I am accessing the managed API from F#. I can construct Z3 expressions using ctx.MkFalse, MkImplies, MkMul etc. but how do i traverse a Z3 expression to discover its structure? Is there something like e.Op or e.IsFalse, e.IsImplies etc.

Motorhead
  • 928
  • 6
  • 16

1 Answers1

3

You should take a look at documentation of Expr.cs.

Here is a simple F# example that traverses through an expression:

let traverse (expr: Expr) =
    printfn "num args: %O" expr.NumArgs
    printfn "children: %A" expr.Args
    printfn "1st child: %O" expr.Args.[0]
    printfn "2nd child: %O" expr.Args.[1]
    printfn "operator: %O" expr.FuncDecl
    printfn "op name: %O" expr.FuncDecl.Name

Expr class also exposes all Term Kind Tests including IsTrue, IsAnd, isImplies, etc which are necessary to discover the structure of an expression. In F# you should define a set of active patterns:

let (|True|_|) (expr: Expr) = if expr.IsTrue then Some() else None
let (|False|_|) (expr: Expr) = if expr.IsFalse then Some() else None

let (|And|_|) (expr: Expr) = if expr.IsAnd then Some expr.Args else None
let (|Or|_|) (expr: Expr) = if expr.IsOr then Some expr.Args else None
let (|Not|_|) (expr: Expr) = if expr.IsNot && expr.NumArgs = 1u 
                             then Some(expr.Args.[0]) else None

let (|Iff|_|) (expr: Expr) = if expr.IsIff && expr.NumArgs = 2u 
                             then Some(expr.Args.[0], expr.Args.[1]) else None
let (|Implies|_|) (expr: Expr) = if expr.IsImplies && expr.NumArgs = 2u 
                                 then Some(expr.Args.[0], expr.Args.[1]) else None

So that you can easily query an expression's structure by pattern matching, even in a recursive way:

match e with
| True -> (* boolean literal *)
| False -> (* boolean literal *)
| And es -> (* query es; possibly by pattern matching *)
| Or es -> (* query es; possibly by pattern matching *)
| Not e' -> (* query e; possibly by pattern matching *)
| Iff(e1, e2) -> (* query e1, e2; possibly by pattern matching *)
| Implies(e1, e2) -> (* query e1, e2; possibly by pattern matching *)
| _ -> (* Not a boolean expression; do something else *)
pad
  • 41,040
  • 7
  • 92
  • 166
  • Of course, they're all sitting in the Expr class - where i forgot to look. My apologies – Motorhead Dec 30 '12 at 02:46
  • 1
    @user1721431: Please consider to accept the answer if it is helpful for you. See [How does accepting an answer work here](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – pad Dec 30 '12 at 09:25