Four bit adder: Difference between revisions

Content added Content deleted
(Added Wren)
(Added parameter types. Some formatting changes. Added some types.)
Line 3,931: Line 3,931:
=={{header|Nim}}==
=={{header|Nim}}==
{{trans|Python}}
{{trans|Python}}
<lang nim>type
<lang nim>proc ha(a, b): auto = [a xor b, a and b] # sum, carry


Bools[N: static int] = array[N, bool]
proc fa(a, b, ci): auto =
SumCarry = tuple[sum, carry: bool]

proc ha(a, b: bool): SumCarry = (a xor b, a and b)

proc fa(a, b, ci: bool): SumCarry =
let a = ha(ci, a)
let a = ha(ci, a)
let b = ha(a[0], b)
let b = ha(a[0], b)
[b[0], a[1] or b[1]] # sum, carry
result = (b[0], a[1] or b[1])


proc fa4(a,b): array[5, bool] =
proc fa4(a, b: Bools[4]): Bools[5] =
var co,s: array[4, bool]
var co, s: Bools[4]
for i in 0..3:
for i in 0..3:
let r = fa(a[i], b[i], if i > 0: co[i-1] else: false)
let r = fa(a[i], b[i], if i > 0: co[i-1] else: false)
Line 3,947: Line 3,952:
result[4] = co[3]
result[4] = co[3]


proc int2bus(n): array[4, bool] =
proc int2bus(n: int): Bools[4] =
var n = n
var n = n
for i in 0..result.high:
for i in 0..result.high:
Line 3,953: Line 3,958:
n = n shr 1
n = n shr 1


proc bus2int(b): int =
proc bus2int(b: Bools): int =
for i,x in b:
for i, x in b:
result += (if x: 1 else: 0) shl i
result += (if x: 1 else: 0) shl i