2 ms·
Ask HN: Logic Gates (in javascript and F#)
in javascript:
var logicGates = {
nand: function (a, b) {
return !(a && b);
},
not: function (a) {
return this.nand(a, a);
},
and: function (a, b) {
return this.not(this.nand(a, b));
},
or: function (a, b) {
return this.nand(this.not(a), logicGates.not(b));
},
nor: function (a, b) {
return this.not(this.or(a, b));
},
xor: function (a, b) {
return this.and(this.nand(a, b), logicGates.or(a, b));
},
xnor: function (a, b) {
return this.not(this.xor(a, b));
}
};
[
{a: false, b: false},
{a: false, b: true},
{a: true, b: false},
{a: true, b: true},
].map(function (x) { return logicGates.nand(x.a, x.b); });
in F#:
type LogicGate =
| ON
| OFF
| NAND of LogicGate * LogicGate
| NOT of LogicGate
| AND of LogicGate * LogicGate
| OR of LogicGate * LogicGate
| NOR of LogicGate * LogicGate
| XOR of LogicGate * LogicGate
| XNOR of LogicGate * LogicGate
let rec evaluate input =
match input with
| ON -> true
| OFF -> false
| NAND(a, b) -> not ((evaluate a) && (evaluate b))
| NOT(a) -> (evaluate (NAND(a, a)))
| AND(a, b) -> (evaluate (NOT(NAND(a, b))))
| OR(a, b) -> (evaluate (NAND(NOT(a), NOT(b))))
| NOR(a, b) -> (evaluate (NOT(OR(a, b))))
| XOR(a, b) -> (evaluate (AND(NAND(a, b), OR(a, b))))
| XNOR(a, b) -> (evaluate (NOT(XOR(a, b))))
[
NAND(OFF, OFF);
NAND(OFF, ON);
NAND(ON, OFF);
NAND(ON, ON)
] |> List.map (fun x -> printfn (evaluate x))
Questions: .
1.) can 'or' and 'xor' be simpler? .
2.) why is it called 'xor'? .
3.) can you add other implementations? .