|
Equivalent C# code (if you want to appreciate the brevity of F# or just understand what the code is doing): public abstract class LogicGate
{
public abstract bool Evaluate();
}
public abstract class BinaryLogic : LogicGate
{
protected LogicGate a, b;
public BinaryLogic(LogicGate a, LogicGate b)
{
this.a = a;
this.b = b;
}
}
public class ON : LogicGate
{
public override bool Evaluate() { return true; }
}
public class OFF : LogicGate
{
public override bool Evaluate() { return false; }
}
public class NAND : BinaryLogic
{
public NAND(LogicGate a, LogicGate b) : base(a, b) { }
public override bool Evaluate()
{
return !(a.Evaluate() && b.Evaluate());
}
}
public class NOT : LogicGate
{
LogicGate a;
public NOT(LogicGate a)
{
this.a = a;
}
public override bool Evaluate()
{
return new NAND(a, a).Evaluate();
}
}
public class AND : BinaryLogic
{
public AND(LogicGate a, LogicGate b) : base(a, b) { }
public override bool Evaluate()
{
return new NOT(new NAND(a, b)).Evaluate();
}
}
public class OR : BinaryLogic
{
public OR(LogicGate a, LogicGate b) : base(a, b) { }
public override bool Evaluate()
{
return new NAND(new NOT(a), new NOT(b)).Evaluate();
}
}
public class NOR : BinaryLogic
{
public NOR(LogicGate a, LogicGate b) : base(a, b) { }
public override bool Evaluate()
{
return new NOT(new OR(a, b)).Evaluate();
}
}
public class XOR : BinaryLogic
{
public XOR(LogicGate a, LogicGate b) : base(a, b) { }
public override bool Evaluate()
{
return new AND(new NAND(a, b), new OR(a, b)).Evaluate();
}
}
public class XNOR : BinaryLogic
{
public XNOR(LogicGate a, LogicGate b) : base(a, b) { }
public override bool Evaluate() { return new NOT(new XOR(a, b)).Evaluate(); }
}
class Program
{
public static void Main(string[] args)
{
var on = new ON();
var off = new OFF();
var result = new List<LogicGate>()
{
new NAND(on, off),
new NAND(off, on),
new NAND(on, off),
new NAND(on, on)
}
.Select(x => x.Evaluate());
Console.WriteLine(result);
}
}
|