I’ve been reading about propositional (or sentential) logic in the book “The Annotated Turing”. I put together a quick console app to write out truth tables. It helped me get the hang of the mathematical notation “v”, “&”, and “->”. In C# those would be ||, &&, and !x || y respectively. I hope someone else finds it useful.
using System; using System.Collections.Generic; namespace PropositionalLogic { public class Program { public class truthvalue { public bool X { get; set; } public bool Y { get; set; } } public static bool XorY(bool x, bool y) { return (x || y); } public static bool XandY(bool x, bool y) { return (x && y); } public static bool Exclusive(bool x, bool y) { return (x && y) && !(x && y);// always false } public static bool Tautoloty(bool x, bool y) { return x || y || (!x && !y);// always true } public static bool Contradition(bool x, bool y) { return x || (y && !y); } public static bool MaterialImplication(bool x, bool y) { return !x || y; //this can also be expressed as the following conjunction !(x && !y); } public static bool BiConditional(bool x, bool y) { return MaterialImplication(x, y) && MaterialImplication(y, x); //"if and only if" } static void Main(string[] args) { var truthTable = new List<truthvalue> { new truthvalue() {X = false, Y = false}, new truthvalue() {X = false, Y = true}, new truthvalue() {X = true, Y = false}, new truthvalue() {X = true, Y = true} }; var sentences = new Dictionary<string , Func<bool, bool, bool>> { {"X v Y", XorY}, {"X & Y", XandY}, {"(x v y)& -(x & y)", Exclusive}, {"x v y v (-x & -y)", Tautoloty}, {"x -> y", MaterialImplication}, {"x ~ y", BiConditional} }; CalculateTruthTable(truthTable, sentences); Console.ReadLine(); } private static void CalculateTruthTable(IEnumerable<truthvalue> truthTable, Dictionary<string , Func<bool, bool, bool>> sentences) { foreach (var sentence in sentences) { Console.WriteLine(""); Console.WriteLine("|X |Y |{0} |", sentence.Key); foreach (var value in truthTable) { var x = value.X; var y = value.Y; var result = sentence.Value(x, y); Console.WriteLine("|{0} |{1} |{2} |", PrettyPrint(x), PrettyPrint(y), PrettyPrint(result)); } } } private static string PrettyPrint(bool input) { return input ? input + " " : input.ToString(); } } }
Leave a Reply