%%% Binary numbers, and some operations on them %%% Author: Frank Pfenning, April 2012 % Binary numbers have some complications, because % the representation is not unique: we can always % add leading zeros. We do not try to maintain any % invariant regarding leading zeros. bit : type. b0 : bit. b1 : bit. nat : type. e : nat. d : nat -o bit -o nat. % Increment inc : nat -> nat -> type. #mode inc + -. inc/e : inc e (d e b1). inc/0 : inc (d M b0) (d M b1). inc/1 : inc (d M b1) (d R b0) o- inc M R. % Decrement dec : nat -> nat -> type. #mode dec + -. % no case for dec/e % 2m-1 = 2(m-1)+1 dec/0 : dec (d M b0) (d N b1) o- dec M N. dec/1 : dec (d M b1) (d M b0). % Addition plus : nat -> nat -> nat -> type. #mode plus + + -. p/e/e : plus e e e. p/e/0 : plus e (d N b0) (d N b0). p/e/1 : plus e (d N b1) (d N b1). p/0/e : plus (d M b0) e (d M b0). p/0/0 : plus (d M b0) (d N b0) (d R b0) o- plus M N R. p/0/1 : plus (d M b0) (d N b1) (d R b1) o- plus M N R. p/1/e : plus (d M b1) e (d M b1). p/1/0 : plus (d M b1) (d N b0) (d R b1) o- plus M N R. p/1/1 : plus (d M b1) (d N b1) (d R b0) o- plus M N K * inc K R. % Less or equal leq : nat -> nat -> type. #mode leq + +. leq/e : leq e N. leq/0/e : leq (d M b0) e o- leq M e. leq/0/0 : leq (d M b0) (d N b0) o- leq M N. leq/0/1 : leq (d M b0) (d N b1) o- leq M N. % no case for leq/1/e % 2m+1 <= 2n iff 2m <= 2n-1 iff 2m <= 2n-2 iff m <= n-1 leq/1/0 : leq (d M b1) (d N b0) o- dec N N1 * leq M N1. leq/1/1 : leq (d M b1) (d N b1) o- leq M N. % Less than lt : nat -> nat -> type. #mode lt + +. % no case for lt/e/e lt/e/0 : lt e (d N b0) o- lt e N. lt/e/1 : lt e (d N b1). % no case for lt/0/e lt/0/0 : lt (d M b0) (d N b0) o- lt M N. lt/0/1 : lt (d M b0) (d N b1) o- leq M N. % no case for lt/1/e % 2m+1 < 2n iff 2m < 2n-1 iff 2m <= 2n-2 iff m <= n-1 lt/1/0 : lt (d M b1) (d N b0) o- dec N N1 * leq M N1. lt/1/1 : lt (d M b1) (d N b1) o- lt M N.