feat(init/data/nat): bitwise operations

This commit is contained in:
Mario Carneiro 2017-05-29 06:20:19 -04:00 committed by Leonardo de Moura
parent d0f73c7041
commit 860e2d904d
3 changed files with 54 additions and 4 deletions

View file

@ -89,12 +89,9 @@ section arith
protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff)
protected def borrow (x y b : bool) :=
bnot x && y || bnot x && b || y && b
-- Subtract with borrow
def sbb (x y : bitvec n) (b : bool) : bool × bitvec n :=
let f := λ x y c, (bitvec.borrow x y c, bitvec.xor3 x y c) in
let f := λ x y c, (bitvec.carry (bnot x) y c, bitvec.xor3 x y c) in
vector.map_accumr₂ f x y b
protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff)

View file

@ -0,0 +1,52 @@
/-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
prelude
import .lemmas init.meta.well_founded_tactics
universe u
namespace nat
def shiftl :
| m 0 := m
| m (n+1) := 2 * shiftl m n
def shiftr :
| m 0 := m
| m (n+1) := shiftr m n / 2
def bodd (n : ) : bool := n % 2 = 1
def test_bit (m n : ) : bool := bodd (shiftr m n)
def binary_rec {α : Type u} (f : bool → αα) (z : α) : α
| 0 := z
| (n+1) := let n' := shiftr (n+1) 1 in
have n' < (n+1), from (div_lt_iff_lt_mul _ _ dec_trivial).2 $
by note := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 2) (succ_pos n);
rwa mul_one at this,
f (bodd (n+1)) n' (binary_rec n')
def size : := binary_rec (λ_ _, succ) 0
def bits : → list bool := binary_rec (λb _ IH, b :: IH) []
def bit (b : bool) : := cond b bit1 bit0
def bitwise (f : bool → bool → bool) : :=
binary_rec
(λa m Ia, binary_rec
(λb n _, bit (f a b) (Ia n))
(bit (f a ff) (Ia 0)))
(binary_rec (λb n Ib, bit (f ff b) Ib) 0)
def lor : := bitwise bor
def land : := bitwise band
def ldiff : := bitwise (λ a b, a && bnot b)
def lxor : := bitwise bxor
end nat

View file

@ -5,3 +5,4 @@ Authors: Leonardo de Moura
-/
prelude
import init.data.nat.basic init.data.nat.div init.data.nat.pow init.data.nat.lemmas
init.data.nat.bitwise