trinary logic with operator overloads lazarus / 62-General ---------------------------------------------------------------------- Kays · 2018-05-04 12:22 Hi, as an exercise I've attempted to implement a (small subset of some) trinary logic using operator overloads (since I barely use them, usually don't want to, but still require having some practice with such). However the attached unit fails compiling saying Code: [Select]trinaryLogic.pas(12,41) Error: Impossible operator overload trinaryLogic.pas(13,44) Error: Impossible operator overloadHow come it's impossible? I've commented out those operator overloads and the overload for * “multiplication” does work, but those two don't? That's confusing. ---------------------------------------------------------------------- Blaazen · 2018-05-04 13:31 I downloaded and tried but no idea. But do not use "true" and "false" it causes troubles. I changed to "_true" and "_false". ---------------------------------------------------------------------- PascalDragon · 2018-05-04 13:43 Operator overloads are not allowed for operators that are already defined by the compiler. The "+" and "-" operators can be used on enum values during their declaration: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TTest = (    One,    Two,    Three,    Four = Three + Two,    Five = Four - One  );And allowing operators in code, but disallowing them during declaration time looks a bit random... Either use other operators or use a record type instead. ---------------------------------------------------------------------- Kays · 2018-05-04 14:19 Quote from: PascalDragon on May 04, 2018, 03:43:40 pm[…] And allowing operators in code, but disallowing them during declaration time looks a bit random... […]Huh, no; + and - are not overloaded for enumeration types but only in their declaration. Compiling Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program foo(input, output, stderr); type        test = (                one,              two,                three,                four = three + two,                five = four - one        ); begin        writeLn(three + two);end.fails due toCode: [Select]foo.pas(13,16) Error: Operation "+" not supported for types "test" and "test"So I don't think those operators are actually defined for enumerations in general. I can't find it documented in the reference guide. And it should not be, since AFAIK an enumeration type is not an integer type, though both are ordinals, but arithmetic operators are only defined for integers and reals. PS: Mustn't it read colon equals four := three + two? ---------------------------------------------------------------------- Thaddy · 2018-05-04 15:33 note the correct expression is ternary logic, not trinary logic. [edit] Oh I see that is allowed : https://en.wikipedia.org/wiki/Three- valued_logic but I never saw that terminology...in computer science papers] Anyway in ternary logic you need to redefine true and false to ternary space. True and false are binary space by convention. And you did so already! But mixed things up a bit. So, as suggested above, either redefine the naming or use a record or enumeration(with three members)  to return the result. Needs to be triplets because of three states. Luckily such syntax is legal in FreePascal. Overloaded operants need not return just true or false..... which is quite a nice feature in this case. As an aside it may be interesting to know that ternary compute in real life computing - as in calculator - (1840, Thomas Fowler) is actually older than today's binary compute systems. Of course Boolean logic itself is from 1847 and had at the time no mechanical or electronical implementation at all.. In your code the problem is just reduced to the use of true and false. Refine - or redefine - that and you're good to go. ---------------------------------------------------------------------- Kays · 2018-05-04 21:32 Quote from: Thaddy on May 04, 2018, 05:33:06 pmnote the correct expression is ternary logic, not trinary logic. […] Yeah, my primary language is German where „trinäre Logik“ sounds closer to „binäre Logik“. Just intuition. Quote from: Thaddy on May 04, 2018, 05:33:06 pm[…] True and false are binary space by convention. And you did so already! But mixed things up a bit. […] Refine - or redefine - that and you're good to go. I've made global substitutions for true and false yet still it doesn't compile. I wanted to make the implementation as easy/trivial as possible (typical for demonstration purposes). Using enumeration types has the “advantage” that succ/pred/ord are operable (out of the box). ---------------------------------------------------------------------- ASerge · 2018-05-05 05:23 I always thought operator overloading only works for structural types. Has that changed? ---------------------------------------------------------------------- Thaddy · 2018-05-05 07:07 Quote from: ASerge on May 05, 2018, 07:23:32 amI always thought operator overloading only works for structural types. Has that changed? Well I just can't overload + and - for some reason, but all the others I can: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}{$H+}type  TMyEnum = (a,b,c);    operator * (const a,b:TMyEnum)c:TMyEnum;  begin    c := TMyEnum(ord(a) * ord(b));  end;        var  aa:TMyEnum;begin  aa := b * c;  writeln(aa);end.This form of operator overloading is already an old feature from 2.x. and {$mode objfpc} not {$mode delphi} What you refer to are probably class operators for records, objects and classes. In the above case there seems to be an issue for addition and substraction only and I think that is a bug, because the compiler only won't accept addition and substraction. - On the one hand it says impossible operator overload for these two, hinting at a default implementation - On the other hand it says enums.pas  Operation "-" not supported for types "TMyEnum" and "TMyEnum". Fair enough, but all others can be overloaded: > >< = * div and or xor not in ** etc. Any thoughts this may warrant a bug report? All this is despite Sven's explanation: seems a contradiction in terms, to some extend. Anyway, ternary truth tables can be build from other operators. ---------------------------------------------------------------------- Kays · 2018-05-05 10:41 Quote from: Thaddy on May 05, 2018, 09:07:52 amWell I just can't overload + and - for some reason, but all the others I can: That's what I reported. Quote from: Thaddy on May 05, 2018, 09:07:52 am[…] In the above case there seems to be an issue for addition and substraction only and I think that is a bug, because the compiler only won't accept addition and substraction. - On the one hand it says impossible operator overload for these two, hinting at a default implementation - On the other hand it says enums.pas  Operation "-" not supported for types "TMyEnum" and "TMyEnum". […] Any thoughts this may warrant a bug report? […](cheery) Yeah! Found another bug (fortunately in a non-critical situation). I know, I can use any other operator, but - and + are quite common notation in electrical engineering, and … OK, I've bluntly attempted overloading not, or and and. And apparently it works, despite not being documented in the diagram. That's where I looked in the first place, since – as I wrote in my first post – I need some practice in operator overloading. The question remains why + and - are “impossible”. I couldn't find any relevant bug report with the terms “operator” and “enum”. ---------------------------------------------------------------------- PascalDragon · 2018-05-05 12:41 Quote from: Kays on May 04, 2018, 04:19:06 pmQuote from: PascalDragon on May 04, 2018, 03:43:40 pm[…] And allowing operators in code, but disallowing them during declaration time looks a bit random... […]Huh, no; + and - are not overloaded for enumeration types but only in their declaration. Sorry, that should have read "And allowing operator overloads in code, but disallowing them during declaration time looks a bit random". If we'd allow allow overloads for + and - operators in code than users might ask for them in declarations as well which wouldn't work as there we have constant expressions. Quote from: Kays on May 04, 2018, 04:19:06 pmPS: Mustn't it read colon equals four := three + two? FPC itself supports both, though the Delphi compatible one is = (:= is even disallowed in Delphi modes). Quote from: Kays on May 05, 2018, 12:41:40 pmOK, I've bluntly attempted overloading not, or and and. And apparently it works, despite not being documented in the diagram. That's where I looked in the first place, since – as I wrote in my first post – I need some practice in operator overloading.Seems like they're indeed missing. Maybe you can issue a bug report towards the Documentation category? Please note that and, or, not and xor exist in both logical and bitwise variations, the former returning Boolean the latter anything suitable. Quote from: Kays on May 05, 2018, 12:41:40 pmThe question remains why + and - are “impossible”. I couldn't find any relevant bug report with the terms “operator” and “enum”. I've already explained to you why that is the case. Quote from: ASerge on May 05, 2018, 07:23:32 amI always thought operator overloading only works for structural types. Has that changed? FPC supports operator overloading for non-records for a long time already, though more restrictions had been placed on which operators overloads were possible. Since AFAIK 2.7.1 essentially all overloads are allowed that aren't already in use by the compiler itself. Please note that global operator overloads have the disadvantage that they can't be used inside a generic (at least not yet, I plan to experiment with that a bit). ---------------------------------------------------------------------- Thaddy · 2018-05-05 15:59 Sven, I found a  bug that is lot more serious while playing with this. See Mantis 0033696. demo code added for interested people: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}{$H+}type  ternary = (F, U, T);     operator and (const a,b:ternary):ternary;inline;    const lookupAnd:array[ternary,ternary] of ternary =                     ((F,F,F),(F,U,U),(F,U,T));  begin    Result:= LookupAnd[a,b];  end;              operator or (const a,b:ternary):ternary;inline;    const lookupOr:array[ternary,ternary] of ternary =                    ((F,U,T),(U,U,T),(T,T,T));  begin    Result := LookUpOr[a,b];  end;          // compiler does not complain here too...., but....  operator not (const a:ternary):ternary;inline;    const LookupNot:array[ternary] of ternary =(T,U,F);  begin     Result:= LookUpNot[a];  end;              begin  // works as expected  writeln('AND');write(F and F);write(F and U);  writeln(F and T);write(U and F);write(U and U);  writeln(U and T);write(T and F);write(T and U);  writeln(T and T);  writeln;  //works as expected  writeln('OR');write(F or F);write(F or U);  writeln(F or T);write(U or F);write(U or U);  writeln(U or T);write(T or F);write(T or U);  writeln(T or T);  writeln;  // this fails, but compiles and runs w/o error indication.  // and renders the wrong results  writeln('NOT');  writeln(not F);// prints -1 instead of T, it does not pick the overload!  writeln(not U);// prints -2 instead of U, it does not pick the overload!  writeln(not T);// prints -3 instead of F, it does not pick the overload!  // which makes this next construct impossible while the compiler suggests it's legal.  {   writeln(T and not F);    }end.Either disallow it or it should be fixed.. This code compiles -Sewhn. Try to remove the comment and see the result from the last - perfectly valid - statement. ---------------------------------------------------------------------- Kays · 2018-05-05 18:12 Quote from: Thaddy on May 05, 2018, 05:59:43 pmSven, […] Who is Sven? Quote from: Thaddy on May 05, 2018, 05:59:43 pmI found a  bug that is lot more serious while playing with this. […] Great. Great, that I gave the impulse to play around with operator overloads and detect bugs. (x.x) Quote from: Thaddy on May 05, 2018, 05:59:43 pmThis code compiles […]Uhm… Weird, my compiler version does not.  Code: [Select]Free Pascal Compiler version 3.0.4+dfsg-11 [2017/12/30] for x86_64 Copyright (c) 1993-2017 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling ohOh.pas ohOh.pas(42,16) Error: Type mismatch ohOh.pas(43,16) Error: Type mismatch ohOh.pas(44,16) Error: Type mismatch ohOh.pas(50) Fatal: There were 3 errors compiling module, stopping Fatal: Compilation aborted Error: /usr/bin/ppcx64 returned an error exitcodeSame with line 47 after uncommenting it. Quote from: PascalDragon on May 05, 2018, 02:41:11 pm[…] Quote from: Kays on May 05, 2018, 12:41:40 pmThe question remains why + and - are “impossible”. I couldn't find any relevant bug report with the terms “operator” and “enum”. I've already explained to you why that is the case. […] But why can't I add/subtract enumeration literals in a statement block? Only during the definition of the type? ---------------------------------------------------------------------- Thaddy · 2018-05-05 19:17 Quote from: Kays on May 05, 2018, 08:12:45 pmQuote from: Thaddy on May 05, 2018, 05:59:43 pmSven, […] Who is Sven?Alias PascalDragon and core developer. Deduction, Watson. QuoteQuote from: Thaddy on May 05, 2018, 05:59:43 pmI found a  bug that is lot more serious while playing with this. […] Great. Great, that I gave the impulse to play around with operator overloads and detect bugs. (x.x) Quote from: Thaddy on May 05, 2018, 05:59:43 pmThis code compiles […]Uhm… Weird, my compiler version does not.  Code: [Select]Free Pascal Compiler version 3.0.4+dfsg-11 [2017/12/30] for x86_64 Copyright (c) 1993-2017 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling ohOh.pas ohOh.pas(42,16) Error: Type mismatch ohOh.pas(43,16) Error: Type mismatch ohOh.pas(44,16) Error: Type mismatch ohOh.pas(50) Fatal: There were 3 errors compiling module, stopping Fatal: Compilation aborted Error: /usr/bin/ppcx64 returned an error exitcodeSame with line 47 after uncommenting it. Then it is a regression or you are using delphi mode. My code is accepted on all my platforms, except the last commented part with FPC trunk. Quote] Quote from: PascalDragon on May 05, 2018, 02:41:11 pm[…] Quote from: Kays on May 05, 2018, 12:41:40 pmThe question remains why + and - are “impossible”. I couldn't find any relevant bug report with the terms “operator” and “enum”. I've already explained to you why that is the case. […] But why can't I add/subtract enumeration literals in a statement block? Only during the definition of the type? Sven explained that. But it is imho open for discussion. ---------------------------------------------------------------------- Thaddy · 2018-05-06 11:23 Note I use trunk, not 3.0.4., and there have been many compiler changes in trunk. In trunk, compiled with -Sew, my code throws no errors, runs, but takes the wrong codepath for the overloaded NOT operator, which makes the commented out and not fail. No errors, no warnings, no option ---------------------------------------------------------------------- Kays · 2018-05-07 20:48 Quote from: Thaddy on May 05, 2018, 09:17:48 pmQuote from: Kays on May 05, 2018, 08:12:45 pmBut why can't I add/subtract enumeration literals in a statement block? Only during the definition of the type? Sven explained that. But it is imho open for discussion. Yeah, I've reviewed all posts by Sven: Quote from: PascalDragon on May 04, 2018, 03:43:40 pmOperator overloads are not allowed for operators that are already defined by the compiler. The "+" and "-" operators can be used on enum values during their declaration:[…]Quote from: PascalDragon on May 05, 2018, 02:41:11 pm[…] "And allowing operator overloads in code, but disallowing them during declaration time looks a bit random". If we'd allow allow overloads for + and - operators in code than users might ask for them in declarations as well which wouldn't work as there we have constant expressions. […]I still don't understand. I try as hard as I can, but I simply can't. Why doesn't the following work?Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program op(input, output, stderr);type        enum = (zero, one, two, three = one + two);begin        writeLn(one + two); // ideally prints threeend. ---------------------------------------------------------------------- Thaddy · 2018-05-08 07:15 Quote from: Kays on May 07, 2018, 10:48:13 pm[Why doesn't the following work?Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program op(input, output, stderr);type        enum = (zero, one, two, three = one + two);begin        writeLn(one + two); // ideally prints threeend.Well, this works: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type enum = (zero, one, two, three = one + two);begin  writeLn(enum(ord(one) + ord(two))); // actually prints threeend.If I only could do that with NOT.... In this case even this works: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type enum = (zero = -5, one = 10, two = 7, three = one + two);begin  writeLn(enum(ord(one) + ord(two))); // actually prints three  writeln(Ord(Three)); // should be 17,right?end.Ok, compiler has a note... I still feel that negation, addition and subtraction should be legal as overloads. Maybe not for enums with assigned values, as the ordinal test shows. That is a hornet's nest. ---------------------------------------------------------------------- Thaddy · 2018-07-08 07:04 @Kays Florian fixed it. In the latest trunk (39406) this now compiles: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$mode objfpc}{$H+}// Kleene and Priest three value logic // See https://en.wikipedia.org/wiki/Three-valued_logictype  ternary = (F, U, T);     operator and (const a,b:ternary):ternary;inline;    const lookupAnd:array[ternary,ternary] of ternary =                     ((F,F,F),(F,U,U),(F,U,T));  begin    Result:= LookupAnd[a,b];  end;          operator or (const a,b:ternary):ternary;inline;    const lookupOr:array[ternary,ternary] of ternary =                    ((F,U,T),(U,U,T),(T,T,T));  begin    Result := LookUpOr[a,b];  end; operator not (const a:ternary):ternary;inline;    const LookupNot:array[ternary] of ternary =(T,U,F);  begin     Result:= LookUpNot[a];  end;     begin  // works as expected  writeln('AND');write(F and F);write(F and U);  writeln(F and T);write(U and F);write(U and U);  writeln(U and T);write(T and F);write(T and U);  writeln(T and T);  writeln;  //works as expected  writeln('OR');write(F or F);write(F or U);  writeln(F or T);write(U or F);write(U or U);  writeln(U or T);write(T or F);write(T or U);  writeln(T or T);  writeln;  // works as expected from rev 39406+  writeln('NOT');  writeln(not F);  writeln(not U);  writeln(not T);  writeln;  // works as expected too  // Material implication for Kleene logic is defined as not(a) or b  writeln('IMP -> not(a) or b');   write(not(T) or T);write(not(U) or T);writeln(not(F) or T);  write(not(T) or U);write(not(U) or U);writeln(not(F) or U);  write(not(T) or F);write(not(U) or F);writeln(not(F) or F);     end. [edit] added test for imp, which is not(a) or b So here we have it. ---------------------------------------------------------------------- Thaddy · 2018-07-08 11:52 I also tested a five way and a nine way logic system. Now also works. Quite impressive that we can do such things and it has really good applicability in electronics and machine learning. Tnx Florian!! (And Kays for bringing it up!!) ---------------------------------------------------------------------- Thaddy · 2018-07-09 13:12 I have attached an implementation of a symmetrically balanced 5-way logic for those who are interested. ---------------------------------------------------------------------- Thaddy · 2018-08-24 18:19 I found similar code on rosettacode today. Gave me some idea's (this one is imho still neater than what's there.) I re-invented wheels again  https://rosettacode.org/wiki/Ternary_logic Strange it didn't show up before in my searches. This logic is now complete, what's missing can all be solved with these basics: it is a neat set of operators suitable for electronics, science, sql and the likes: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program ternarytests;{$mode objfpc}{* Evaluated, added XOR, and tested against other languages after seeing code on rosettacode. * They used almost all similar code. So I decided to finish it*   Currently the equality operator can not be overridden for equal types but  1. equality is the same as: NOT (x XOR y)  2. IMP is the same as: (NOT x) OR y  So these two demonstrate the logic works!    Enjoy,     Thaddy}type  { ternary type }  trit = (F, U, T);     operator and (const a,b:trit):trit;inline;    const lookupAnd:array[trit,trit] of trit =                   ((F,F,F),(F,U,U),(F,U,T));  begin    Result:= LookupAnd[a,b];  end;            operator or (const a,b:trit):trit;inline;    const lookupOr:array[trit,trit] of trit =                  ((F,U,T),(U,U,T),(T,T,T));  begin    Result := LookUpOr[a,b];  end;    operator not (const a:trit):trit;inline;    const LookupNot:array[trit] of trit =(T,U,F);  begin     Result:= LookUpNot[a];  end;     operator xor (const a,b:trit):trit;    const LookupXor:array[trit,trit] of trit =     ((F,U,T),(U,U,U),(T,U,F));  begin    Result := LookupXor[a,b];  end; // just tests... begin  writeln(' a AND b');  writeln('__FUT');  writeln('F|',F and F,F and U,F and T);  writeln('U|',U and F,U and U,U and T);  writeln('T|',T and F,T and U,T and T);  writeln;    writeln(' a OR b');  writeln('__FUT');  writeln('F|',F or F,F or U,F or T);  writeln('U|',U or F,U or U,U or T);  writeln('T|',T or F,T or U,T or T);  writeln;  writeln(' NOT a');  writeln('__FUT');  writeln('F|',not F);  writeln('U|',not U);  writeln('T|',not T);  writeln;    writeln(' a XOR b');  writeln('__FUT');  writeln('F|',F xor F,F xor U,F xor T);  writeln('U|',U xor F,U xor U,U xor T);  writeln('T|',T xor F,T xor U,T xor T);  writeln;   writeln(' NOT (a  XOR b)  -> equality/equivalence');  writeln('__FUT');  writeln('F|',not(F xor F),not(F xor U),not(F xor T));  writeln('U|',not(U xor F),not(U xor U),not(U xor T));  writeln('T|',not(T xor F),not(T xor U),not(T xor T));  writeln;   writeln('IMP. a.k.a. IfThen -> not(a) or b');   writeln('T|',(not T) or T,(not T) or U,(not T) or F);  writeln('U|',(not U) or T,(not U) or U,(not U) or F);  writeln('F|',(not F) or T,(not F) or U,(not F) or F);end. This is a Kleene and Priest logic as per OP's original question. I will introduce the XOR operation in my five way logic too and will add a nine way logic. (The latter two can be used for de-fuzzing fuzzy logic, for which I wrote operators too) I think it can't be written much simpler than that! ---------------------------------------------------------------------- Thaddy · 2018-08-25 14:34 Here's the fuzzy part: Zadeh's classic standard fuzzy logic: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program zadehlogic;{$mode objfpc}{$notes off}{ Zadeh's standard fuzzy logic operators  See:    https://commons.wikimedia.org/wiki/Fuzzy_operator  Don't let your eyes fool you, these are not integer or boolean  calculations, but floating point calculations!.   Enjoy,   Thaddy }type  { Fuzz is a double in the inclusive range 0..1    The programmer is responsible for valid input.    (You can use EnsureRange from the math unit.) }  Fuzz = type double;   { helpers }    function min(const a,b:Fuzz):Fuzz;inline;  begin        if a > b then result := b else result := a;  end;   function max(const a,b:Fuzz):Fuzz;inline;  begin      if b > a then result := b else result := a;  end; { the basic logic }    { AND is defined as min(a, b) in standard fuzzy logic }  operator and (const a,b:Fuzz):Fuzz;inline;  begin    Result:=min(a,b);  end;   { OR is defined as max(a,b) in standard fuzzy logic }  operator or (const a,b:Fuzz):Fuzz;inline;  begin    Result:=max(a, b);  end;    { NOT is simply the inverse, given a range of 0..1. Comparable to Boolean}  operator not (const a:Fuzz):Fuzz;inline;  begin    result := 1 - a;  end;    { XOR. See AND how this reflects: the bias to either a or b gets amplified  }  operator xor (const a,b:Fuzz):Fuzz;inline;  begin    result := a + b - 2 * (a and b);  end;  { not overloaded logic as functions: all can be derived from the above four }   { IMP }  function imp(const a,b:Fuzz):Fuzz;inline;  begin    Result := not (a and not b)  end;    { NAND }  function nand(const a,b:Fuzz):Fuzz;inline;  begin    Result := not (a and b);  end;    { NOR }  function nor(const a,b:Fuzz):Fuzz;inline;  begin    Result := not (a or b);  end;    { NXR }  function nxr(const a,b:Fuzz):Fuzz;inline;  begin    Result := not (a xor b);  end;    { NIMP }  function nimp(const a,b:Fuzz):Fuzz;inline;  begin    Result := a and not b;  end;   beginend.