function xor_gate(bool a, bool b) return (a and not b) or (not a and b) end function function half_adder(bool a, bool b) bool s = xor_gate(a,b) bool c = a and b return {s,c} end function function full_adder(bool a, bool b, bool c) bool {s1,c1} = half_adder(c,a) bool {s2,c2} = half_adder(s1,b) c = c1 or c2 return {s2,c} end function function four_bit_adder(bool a0, a1, a2, a3, b0, b1, b2, b3) bool s0,s1,s2,s3,c {s0,c} = full_adder(a0,b0,0) {s1,c} = full_adder(a1,b1,c) {s2,c} = full_adder(a2,b2,c) {s3,c} = full_adder(a3,b3,c) return {s3,s2,s1,s0,c} end function procedure test(integer a, integer b) bool {a0,a1,a2,a3} = int_to_bits(a,4) bool {b0,b1,b2,b3} = int_to_bits(b,4) bool {r3,r2,r1,r0,c} = four_bit_adder(a0,a1,a2,a3,b0,b1,b2,b3) integer r = bits_to_int({r0,r1,r2,r3}) printf(1,"%04b + %04b = %04b %b (%d+%d=%d)\n",{a,b,r,c,a,b,c*16+r}) end procedure test(0,0) test(0,1) test(0b1111,0b1111) test(3,7) test(11,8) test(0b1100,0b1100) test(0b1100,0b1101) test(0b1100,0b1110) test(0b1100,0b1111) test(0b1101,0b0000) test(0b1101,0b0001) test(0b1101,0b0010) test(0b1101,0b0011)