5

I want to encode If-the-else in Z3 python, but cannot find any docs or sample on how to do that.

I have a sample code like below.

F = True
tmp = BitVec('tmp', 1)
tmp1 = BitVec('tmp1', 8)

Now how can I encode this condition into F:

if tmp == 1, then tmp1 == 100. otherwise, tmp1 == 0 

Thanks so much.

user311703
  • 1,113
  • 2
  • 14
  • 25

2 Answers2

12

You'll need Z3's If function:

def z3py.If   (       a,
          b,
          c,
          ctx = None 
  )   

Create a Z3 if-then-else expression.

>>> x = Int('x')
>>> y = Int('y')
>>> max = If(x > y, x, y)
>>> max
If(x > y, x, y)
>>> simplify(max)
If(x <= y, y, x)

(from here)

Ilmo Euro
  • 4,925
  • 1
  • 27
  • 29
5

You can use If for this. If takes three arguments: the condition, an expression that should be true if the condition is true and an expression that should be true if the condition is false. So to express your logic, you'd write:

If(tmp==1, tmp1==100, tmp1==0)
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Are you sure it can be used this way? Based on the examples I see online, it is always used as the (?:) operator in C++ (e.g., y = condition? x1 : x2). I am actually looking for something to represent IF-THEN, other than "Implies". – Mohammed Nov 22 '20 at 05:05
  • @Mohammed I don't see a difference between OP's `if tmp == 1, then tmp1 == 100. otherwise, tmp1 == 0 ` and `tmp == 1 ? tmp1 == 100 : tmp1 == 0`. It seems to me that those are just two different notations to express the same thing. – sepp2k Nov 22 '20 at 12:55
  • Ok @sepp2k, thank you. I meant this `tmp1 = (tmp == 1)? 100 : 0` I am not 100% sure but it may be the same if we're assigning the same variable, compared to `tmp == 1? tmp1 == 100 : tmp2 == 0`. Anyway, I just realized it is a 7-years old post. Thanks for the reply. – Mohammed Nov 28 '20 at 21:24
  • @Mohammed I'm not entirely sure what you mean. Z3 doesn't have a concept of assignment. If you're analysing some programming language, then a construct like `tmp1 = (tmp == 1)? 100 : 0` in that language could indeed be modelled as `If(tmp==1, tmp1==100, tmp1==0)` in Z3, assuming the variables are never reassigned. – sepp2k Nov 28 '20 at 22:01