RosettaCodeData/Task/Four-bit-adder/Ballerina/four-bit-adder.ballerina
2025-06-11 20:16:52 -04:00

31 lines
834 B
Text

import ballerina/io;
function xor(byte a, byte b) returns byte {
return a & (~b) | b & (~a);
}
function ha(byte a, byte b) returns [byte, byte] {
return [xor(a, b), a & b];
}
function fa(byte a, byte b, byte c0) returns [byte, byte] {
var [sa, ca] = ha(a, c0);
var [s, cb] = ha(sa, b);
var c1 = ca | cb;
return [s, c1];
}
function add4(byte a3, byte a2, byte a1, byte a0, byte b3, byte b2, byte b1, byte b0)
returns [byte, byte, byte, byte, byte] {
var [s0, c0] = fa(a0, b0, 0);
var [s1, c1] = fa(a1, b1, c0);
var [s2, c2] = fa(a2, b2, c1);
var [s3, v] = fa(a3, b3, c2);
return [v, s3, s2, s1, s0];
}
public function main() {
// add 10+9 result should be [1, 0, 0, 1, 1]
var sum = add4(1, 0, 1, 0, 1, 0, 0, 1);
io:println(re `,`.replaceAll(sum.toString(), ", "));
}