Ternary logic: Difference between revisions

28,794 bytes added ,  14 days ago
(Ternary logic en TrueBASIC)
(41 intermediate revisions by 24 users not shown)
Line 93:
Note:   '''[[wp:Setun|Setun]]'''   (Сетунь) was a   [[wp:balanced ternary|balanced ternary]]   computer developed in 1958 at   [[wp:Moscow State University|Moscow State University]].   The device was built under the lead of   [[wp:Sergei Sobolev|Sergei Sobolev]]   and   [[wp:Nikolay Brusentsov|Nikolay Brusentsov]].   It was the only modern   [[wp:ternary computer|ternary computer]],   using three-valued [[wp:ternary logic|ternary logic]]
<br><br>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE TERNARY="BYTE"
DEFINE FALSE="0"
DEFINE MAYBE="1"
DEFINE TRUE="2"
 
PROC PrintT(TERNARY a)
IF a=FALSE THEN Print("F")
ELSEIF a=MAYBE THEN Print("?")
ELSE Print("T")
FI
RETURN
 
TERNARY FUNC NotT(TERNARY a)
RETURN (TRUE-a)
 
TERNARY FUNC AndT(TERNARY a,b)
IF a<b THEN RETURN (a) FI
RETURN (b)
 
TERNARY FUNC OrT(TERNARY a,b)
IF a>b THEN RETURN (a) FI
RETURN (b)
 
TERNARY FUNC IfThenT(TERNARY a,b)
IF a=TRUE THEN RETURN (b)
ELSEIF a=FALSE THEN RETURN (TRUE)
ELSEIF a+b>TRUE THEN RETURN (TRUE)
FI
RETURN (MAYBE)
 
TERNARY FUNC EquivT(TERNARY a,b)
IF a=b THEN RETURN (TRUE)
ELSEIF a=TRUE THEN RETURN (b)
ELSEIF b=TRUE THEN RETURN (a)
FI
RETURN (MAYBE)
 
PROC Main()
BYTE x,y,a,b,res
 
x=2 y=1
FOR a=FALSE TO TRUE
DO
res=NotT(a)
Position(x,y) y==+1
Print("not ") PrintT(a)
Print(" = ") PrintT(res)
OD
 
y==+1
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=AndT(a,b)
Position(x,y) y==+1
PrintT(a) Print(" and ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
 
y==+1
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=OrT(a,b)
Position(x,y) y==+1
PrintT(a) Print(" or ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
 
x=20 y=5
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=IfThenT(a,b)
Position(x,y) y==+1
Print("if ") PrintT(a)
Print(" then ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
 
y==+1
FOR a=FALSE TO TRUE
DO
FOR b=FALSE TO TRUE
DO
res=EquivT(a,b)
Position(x,y) y==+1
PrintT(a) Print(" equiv ") PrintT(b)
Print(" = ") PrintT(res)
OD
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Ternary_logic.png Screenshot from Atari 8-bit computer]
<pre>
not F = T
not ? = ?
not T = F
 
F and F = F if F then F = T
F and ? = F if F then ? = T
F and T = F if F then T = T
? and F = F if ? then F = ?
? and ? = ? if ? then ? = ?
? and T = ? if ? then T = T
T and F = F if T then F = F
T and ? = ? if T then ? = ?
T and T = T if T then T = T
 
F or F = F F equiv F = T
F or ? = ? F equiv ? = ?
F or T = T F equiv T = F
? or F = ? ? equiv F = ?
? or ? = ? ? equiv ? = T
? or T = T ? equiv T = ?
T or F = T T equiv F = F
T or ? = T T equiv ? = ?
T or T = T T equiv T = T
</pre>
 
=={{header|Ada}}==
 
We first specify a package "Logic" for three-valued logic. Observe that predefined Boolean functions, "and" "or" and "not" are overloaded:
<langsyntaxhighlight Adalang="ada">package Logic is
type Ternary is (True, Unknown, False);
 
Line 111 ⟶ 238:
function To_Ternary(B: Boolean) return Ternary;
function Image(Value: Ternary) return Character;
end Logic;</langsyntaxhighlight>
 
Next, the implementation of the package:
 
<langsyntaxhighlight Adalang="ada">package body Logic is
-- type Ternary is (True, Unknown, False);
 
Line 176 ⟶ 303:
end Implies;
 
end Logic;</langsyntaxhighlight>
 
Finally, a sample program:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Logic;
 
procedure Test_Tri_Logic is
Line 213 ⟶ 340:
Truth_Table(F => Equivalent'Access, Name => "Eq");
Truth_Table(F => Implies'Access, Name => "Implies");
end Test_Tri_Logic;</langsyntaxhighlight>
 
{{out}}
Line 239 ⟶ 366:
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: Ternary_logic.a68'''
<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
INT trit width = 1, trit base = 3;
Line 337 ⟶ 464:
#true # (false, maybe, true )
)[@-1,@-1][INITINT a, INITINT b]
);</langsyntaxhighlight>'''File: Template_operators_logical_mixin.a68'''
<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
OP & = (LOGICAL a,b)LOGICAL: a AND b;
Line 362 ⟶ 489:
OP ~ = (LOGICAL a)LOGICAL: NOT a,
~= = (LOGICAL a,b)LOGICAL: a /= b; SCALAR!
FI#</langsyntaxhighlight>'''File: test_Ternary_logic.a68'''
<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 432 ⟶ 559:
print trit op table("⊃","IMPLIES", (TRIT a,b)TRIT: a IMPLIES b);
print trit op table("∧","AND", (TRIT a,b)TRIT: a AND b);
print trit op table("∨","OR", (TRIT a,b)TRIT: a OR b)</langsyntaxhighlight>
{{out}}
<pre>
Line 495 ⟶ 622:
Arturo's '':logical'' values inherently support ternary logic (<code>true</code>, <code>false</code> and <code>maybe</code>) and the corresponding logical operations.
 
<langsyntaxhighlight lang="rebol">vals: @[true maybe false]
 
loop vals 'v -> print ["NOT" v "=>" not? v]
Line 512 ⟶ 639:
loop vals 'v2
-> print [v1 "XOR" v2 "=>" xor? v1 v2]
]</langsyntaxhighlight>
 
{{out}}
Line 552 ⟶ 679:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Ternary_Not(a){
SetFormat, Float, 2.1
return Abs(a-1)
Line 571 ⟶ 698:
Ternary_Equiv(a,b){
return a=b?1:a=1?b:b=1?a:0.5
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">aa:=[1,0.5,0]
bb:=[1,0.5,0]
 
Line 602 ⟶ 729:
StringReplace, Res, Res, 0, false, all
MsgBox % Res
return</langsyntaxhighlight>
{{out}}
<pre> Ternary_Not true = false
Line 651 ⟶ 778:
=={{header|BASIC256}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="lb">
<lang lb>
global tFalse, tDontKnow, tTrue
tFalse = 0
Line 722 ⟶ 849:
end case
end function
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 730 ⟶ 857:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$ + "CLASSLIB"
REM Create a ternary class:
Line 775 ⟶ 902:
PRINT "TRUE EQV TRUE = " FN(mytrit.teqv)("TRUE","TRUE")
PROC_discard(mytrit{})</langsyntaxhighlight>
{{out}}
<pre>
Line 806 ⟶ 933:
MAYBE EQV TRUE = MAYBE
TRUE EQV TRUE = TRUE
</pre>
 
=={{header|Bruijn}}==
Direct translations of the truth tables to lambda calculus. The operators could be golfed significantly. If you do so, please add them here!
 
For applications of Ternary logic, see bruijn's [[Balanced_ternary#Bruijn|balanced ternary]] implementation.
<syntaxhighlight lang="bruijn">
true [[[0]]]
 
maybe [[[1]]]
 
false [[[2]]]
 
¬‣ [0 true maybe false]
 
…⋀… [[1 (0 1 1 1) (0 0 0 1) (0 0 0 0)]]
 
…⋁… [[1 (0 0 0 0) (0 1 0 0) (0 1 1 1)]]
 
…⊃… [[1 (0 true 0 1) (0 true 1 1) (0 1 1 1)]]
 
…≡… [[1 (0 true 0 1) (0 1 1 1) (0 0 0 0)]]
 
# --- result samples ---
 
:import std/List .
 
main [[inp <> "=" <> !res ++ "\n"] <++> (cross3 ops trits trits)]
!‣ [0 "false" "maybe" "true"]
…<>… [[1 ++ " " ++ 0]]
inp 0 [[~1 <> (0 [[!1 <> (0 [[!1]])]])]]
res ^(^0) ^(~0) ^(~(~0))
ops (…⋀… : "and") : ((…⋁… : "or") : ((…⊃… : "if") : {}(…≡… : "equiv")))
trits true : (maybe : {}false)
</syntaxhighlight>
 
{{out}}
<pre>
and true true = true
and true maybe = maybe
and true false = false
and maybe true = maybe
and maybe maybe = maybe
and maybe false = false
and false true = false
and false maybe = false
and false false = false
or true true = true
or true maybe = true
or true false = true
or maybe true = true
or maybe maybe = maybe
or maybe false = maybe
or false true = true
or false maybe = maybe
or false false = false
if true true = true
if true maybe = true
if true false = true
if maybe true = maybe
if maybe maybe = maybe
if maybe false = true
if false true = false
if false maybe = maybe
if false false = true
equiv true true = true
equiv true maybe = maybe
equiv true false = false
equiv maybe true = maybe
equiv maybe maybe = maybe
equiv maybe false = maybe
equiv false true = false
equiv false maybe = maybe
equiv false false = true
</pre>
 
=={{header|C}}==
===Implementing logic using lookup tables===
<langsyntaxhighlight lang="c">#include <stdio.h>
typedef enum {
Line 880 ⟶ 1,081:
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 928 ⟶ 1,129:
 
===Using functions===
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef enum { t_F = -1, t_M, t_T } trit;
Line 963 ⟶ 1,164:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[Not]
Line 1,004 ⟶ 1,205:
the result is randomly sampled to true or false according to the chance.
(This description is definitely very confusing perhaps).
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,058 ⟶ 1,259:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
/// <summary>
Line 1,105 ⟶ 1,306:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>¬True = False
Line 1,149 ⟶ 1,350:
=={{header|C++}}==
Essentially the same logic as the [[#Using functions|Using functions]] implementation above, but using class-based encapsulation and overridden operators.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <stdlib.h>
 
Line 1,222 ⟶ 1,423:
show_op(==);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
{{out}}
<pre>! ----
Line 1,254 ⟶ 1,455:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun tri-not (x) (- 1 x))
(defun tri-and (&rest x) (apply #'* x))
(defun tri-or (&rest x) (tri-not (apply #'* (mapcar #'tri-not x))))
Line 1,284 ⟶ 1,485:
(print-table #'tri-or "OR")
(print-table #'tri-imply "IMPLY")
(print-table #'tri-eq "EQUAL")</langsyntaxhighlight>
{{out}}
<pre>NOT:
Line 1,321 ⟶ 1,522:
=={{header|D}}==
Partial translation of a C entry:
<langsyntaxhighlight lang="d">import std.stdio;
 
struct Trit {
Line 1,388 ⟶ 1,589:
showOperation!"=="("Equiv");
showOperation!"==>"("Imply");
}</langsyntaxhighlight>
{{out}}
<pre>[Not]
Line 1,431 ⟶ 1,632:
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">unit TrinaryLogic;
 
interface
Line 1,486 ⟶ 1,687:
end;
 
end.</langsyntaxhighlight>
 
And that's the reason why you never on no account ''ever'' should compare against the values of True or False unless you intent ternary logic!
 
An alternative version would be using an enum type
<langsyntaxhighlight lang="delphi">type TriBool = (tbFalse, tbMaybe, tbTrue);</langsyntaxhighlight>
and defining a set of constants implementing the above tables:
<langsyntaxhighlight lang="delphi">const
tvl_not: array[TriBool] = (tbTrue, tbMaybe, tbFalse);
tvl_and: array[TriBool, TriBool] = (
Line 1,515 ⟶ 1,716:
(tbFalse, tbMaybe, tbTrue),
);
</syntaxhighlight>
</lang>
 
That's no real fun, but lookup can then be done with
<langsyntaxhighlight lang="delphi">Result := tvl_and[A, B];</langsyntaxhighlight>
 
=={{header|EasyLang}}==
{{trans|FreeBASIC}}
<syntaxhighlight>
sym$[] = [ "F" "?" "T" ]
arrbase sym$[] -1
#
func tnot x .
return -x
.
func tand x y .
if x > y
return tand y x
.
return x
.
func tor x y .
if x < y
return tor y x
.
return x
.
func teqv x y .
return x * y
.
func timp x y .
if -y > x
return -y
.
return x
.
print " (AND) ( OR) (EQV) (IMP) (NOT)"
print " F ? T F ? T F ? T F ? T "
print " -----------------------------------------"
for i = -1 to 1
o$ = " " & sym$[i] & " | "
o$ &= sym$[tand -1 i] & " " & sym$[tand 0 i] & " " & sym$[tand 1 i]
o$ &= " "
o$ &= sym$[tor -1 i] & " " & sym$[tor 0 i] & " " & sym$[tor 1 i]
o$ &= " "
o$ &= sym$[timp -1 i] & " " & sym$[timp 0 i] & " " & sym$[timp 1 i]
o$ &= " "
o$ &= sym$[timp -1 i] & " " & sym$[timp 0 i] & " " & sym$[timp 1 i]
o$ &= " " & sym$[tnot i]
print o$
.
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import system'collections;
Line 1,528 ⟶ 1,776:
sealed class Trit
{
bool _value;
bool cast() = _value;
constructor(object v)
{
if (v != nil)
{
_value := cast bool(v);
}
}
Trit equivalent(b)
{
= _value.equal(cast bool(b)) \ back:nilValue;
var val2 := cast bool(b) \ back(nil);
 
if (val2 != nil && _value != nil)
{
^ _value.equal(val2)
};
 
^ nilValue;
}
Trit Inverted
= _value.Inverted \ back:(nilValue);
Trit and(b)
{
if (nil == _value)
{
^ b.and:(nil) \ back:(nilValue)
}
else
{
^ _value.and((lazy:cast bool(b))) \ back:(nilValue)
}
}
Trit or(b)
{
if (nil == _value)
{
^ b.or:(nilValue) \ back:(nilValue)
}
else
{
^ _value.or((lazy:cast bool(b))) \ back:(nilValue)
}
}
Trit implies(b)
= self.Inverted.or(b);
string toPrintable() = _value.toPrintable() \ back:("maybe");
}
Line 1,579 ⟶ 1,836:
{
List<Trit> values := new Trit[]{true, nilValue, false};
values.forEach::(left)
{
console.printLine("¬",left," = ", left.Inverted);
values.forEach::(right)
{
console.printLine(left, " & ", right, " = ", left && right);
console.printLine(left, " | ", right, " = ", left || right);
console.printLine(left, " → ", right, " = ", left.implies:(right));
console.printLine(left, " ≡ ", right, " = ", left.equivalent:(right))
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,635 ⟶ 1,892:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">% Implemented by Arjun Sunel
-module(ternary).
-export([main/0, nott/1, andd/2,orr/2, then/2, equiv/2]).
Line 1,709 ⟶ 1,966:
io: format("~s\n", [B])
end.
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
For boolean logic, Factor uses ''t'' and ''f'' with the words ''>boolean'', ''not'', ''and'', ''or'', ''xor''. For ternary logic, we add ''m'' and define the words ''>trit'', ''tnot'', ''tand'', ''tor'', ''txor'' and ''t=''. Our new class, ''trit'', is the union class of ''t'', ''m'' and ''f''.
 
<langsyntaxhighlight lang="factor">! rosettacode/ternary/ternary.factor
! http://rosettacode.org/wiki/Ternary_logic
USING: combinators kernel ;
Line 1,754 ⟶ 2,011:
{ m [ >trit drop m ] }
{ f [ tnot ] }
} case ;</langsyntaxhighlight>
 
Example use:
<langsyntaxhighlight lang="factor">( scratchpad ) CONSTANT: trits { t m f }
( scratchpad ) trits [ tnot ] map .
{ f m t }
Line 1,767 ⟶ 2,024:
{ { f m t } { m m m } { t m f } }
( scratchpad ) trits [ trits swap [ t= ] curry map ] map .
{ { t m f } { m m m } { f m t } }</langsyntaxhighlight>
 
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
 
Standard Forth defines flags 'false' as 0 and 'true' as -1 (all bits set). We thus define 'maybe' as 1 to keep standard binary logic as-is and seamlessly include ternary logic. We may have use truthtables but here functions are more fluid.
 
<syntaxhighlight lang="forth">1 constant maybe
 
: tnot dup maybe <> if invert then ;
: tand and ;
: tor or ;
: tequiv 2dup and rot tnot rot tnot and or ;
: timply tnot tor ;
: txor tequiv tnot ;
 
: t. C" TF?" 2 + + c@ emit ;
 
: table2. ( xt -- )
cr ." T F ?"
cr ." --------"
2 true DO
cr I t. ." | "
2 true DO
dup I J rot execute t. ." "
LOOP
LOOP DROP ;
 
: table1. ( xt -- )
2 true DO
CR I t. ." | "
dup I swap execute t.
LOOP DROP ;
 
CR ." [NOT]" ' tnot table1. CR
CR ." [AND]" ' tand table2. CR
CR ." [OR]" ' tor table2. CR
CR ." [XOR]" ' txor table2. CR
CR ." [IMPLY]" ' timply table2. CR
CR ." [EQUIV]" ' tequiv table2. CR
</syntaxhighlight>
 
{{out}}
<pre>[NOT]
T | F
F | T
? | ?
 
[AND]
T F ?
--------
T | T F ?
F | F F F
? | ? F ?
 
[OR]
T F ?
--------
T | T T T
F | T F ?
? | T ? ?
 
[XOR]
T F ?
--------
T | F T ?
F | T F ?
? | ? ? ?
 
[IMPLY]
T F ?
--------
T | T F ?
F | T T T
? | T ? ?
 
[EQUIV]
T F ?
--------
T | T F ?
F | F T ?
? | ? ? ?
</pre>
 
As Forth is a concatenative language, ternary logic use appears seamless:
<pre>: optimist CR or if ." yes !" else ." no..." then ; ok
true maybe optimist
yes ! ok
maybe false optimist
yes ! ok
maybe maybe optimist
yes ! ok
false false optimist
no... ok
</pre>
 
 
=={{header|Fortran}}==
 
Please find the demonstration and compilation with gfortran at the start of the code. A module contains the ternary logic for easy reuse. Consider input redirection from unixdict.txt as vestigial. Or I could delete it.
<syntaxhighlight lang="fortran">
<lang FORTRAN>
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon May 20 23:05:46
Line 1,870 ⟶ 2,223:
 
end program ternaryLogic
</syntaxhighlight>
</lang>
 
=={{header|Free Pascal}}==
Line 1,876 ⟶ 2,229:
Note equivalence and implication are used as proof, they are solved using the basic set instead of a lookup.
Note Since we use a balanced range -1,0,1 multiplication equals EQU
<langsyntaxhighlight lang="pascal">{$mode objfpc}
unit ternarylogic;
 
Line 1,942 ⟶ 2,295:
end;
end.
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="pascal">program ternarytests;
{$mode objfpc}
uses
Line 1,988 ⟶ 2,341:
writeln('F|',tFalse >< tTrue:7, tFalse >< tMaybe:7,tFalse >< tFalse:7);
writeln;
end.</langsyntaxhighlight>
<pre>
Output:
Line 2,028 ⟶ 2,381:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">enum trit
F=-1, M=0, T=1
end enum
Line 2,072 ⟶ 2,425:
outstr += " " + symbol(not(i))
print outstr
next i</langsyntaxhighlight>
<pre>
(AND) ( OR) (EQV) (IMP) (NOT)
Line 2,082 ⟶ 2,435:
</pre>
 
<!--
=={{header|Fōrmulæ}}==
 
Line 2,093 ⟶ 2,447:
 
The solution also shows how to ''redefine'' the logic operations, and how to show the values and the operations using colors.
-->
 
=={{header|Go}}==
Go has four operators for the bool type: ==, &&, ||, and !.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,170 ⟶ 2,525:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,214 ⟶ 2,569:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">enum Trit {
TRUE, MAYBE, FALSE
Line 2,231 ⟶ 2,586:
Trit imply(Trit that) { this.nand(that.not()) }
Trit equiv(Trit that) { this.and(that).or(this.nor(that)) }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">printf 'AND\n '
Trit.values().each { b -> printf ('%6s', b) }
println '\n ----- ----- -----'
Line 2,273 ⟶ 2,628:
Trit.values().each { b -> printf ('%6s', a.equiv(b)) }
println()
}</langsyntaxhighlight>
 
{{out}}
Line 2,313 ⟶ 2,668:
All operations given in terms of NAND, the functionally-complete operation.
 
<langsyntaxhighlight Haskelllang="haskell">import Prelude hiding (Bool(..), not, (&&), (||), (==))
 
main = mapM_ (putStrLn . unlines . map unwords)
Line 2,349 ⟶ 2,704:
where header = map (:[]) (take ((length $ head xs) - 1) ['A'..]) ++ [name]
 
pad s = s ++ replicate (5 - length s) ' '</langsyntaxhighlight>
 
{{out}}
Line 2,409 ⟶ 2,764:
 
 
<langsyntaxhighlight Iconlang="icon">$define TRUE 1
$define FALSE -1
$define UNKNOWN 0
Line 2,470 ⟶ 2,825:
procedure xor3(a,b) #: xor of two trits or error if invalid
return not3(eq3(a,b))
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 2,521 ⟶ 2,876:
maybe: 0.5
 
<langsyntaxhighlight lang="j">not=: -.
and=: <.
or =: >.
if =: (>. -.)"0~
eq =: (<.&-. >. <.)"0</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> not 0 0.5 1
1 0.5 0
 
Line 2,550 ⟶ 2,905:
1 0.5 0
0.5 0.5 0.5
0 0.5 1</langsyntaxhighlight>
 
Note that this implementation is a special case of "[[wp:fuzzy logic|fuzzy logic]]" (using a limited set of values).
 
Note that while <code>>.</code> and <code><.</code> could be used for boolean operations instead of J's <code>+.</code> and <code>*.</code>, the identity elements for >. and <. are not boolean1 valuesand 0, but are negative and positive infinity. See also: [[wp:Boolean ring|Boolean ring]]
 
Note that we might instead define values between 0 and 1 to represent independent probabilities:
 
<langsyntaxhighlight Jlang="j">not=: -.
and=: *
or=: *&.-.
if =: (or -.)"0~
eq =: (*&-. or *)"0</langsyntaxhighlight>
 
However, while this might be a more intellectually satisfying approach, this gives us some different results from the task requirement, for the combination of two "maybe" values (we could "fix" this by adding some "logic" which replaced any non-integer value with "0.5" - this would satisfy literal compliance with the task specification and might even be a valid engineering choice if we are implementing in hardware, for example):
 
<langsyntaxhighlight Jlang="j"> not 0 0.5 1
1 0.5 0
 
Line 2,587 ⟶ 2,942:
1 0.5 0
0.5 0.4375 0.5
0 0.5 1</langsyntaxhighlight>
 
Another interesting possibility would involve using George Boole's original operations. This leaves us without any "not", (if we include the definition of logical negation which was later added to the definition of Boolean algebra, then the only numbers which can be used with Boolean algebra are 1 and 0). So, it's not clear how we would implement "if" or "eq". However, "and" and "or" would look like this:
 
<langsyntaxhighlight Jlang="j">and=: *.
or=: +.</langsyntaxhighlight>
 
And, the boolean result tables would look like this:
 
<langsyntaxhighlight Jlang="j"> 0 0.5 1 and/ 0 0.5 1
0 0 0
0 0.5 1
Line 2,604 ⟶ 2,959:
0 0.5 1
0.5 0.5 0.5
1 0.5 1</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class Logic{
public static enum Trit{
TRUE, MAYBE, FALSE;
Line 2,675 ⟶ 3,030:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>not TRUE: FALSE
Line 2,693 ⟶ 3,048:
Let's use the trit already available in JavaScript:
true, false (both boolean) and undefined…
<langsyntaxhighlight JavaScriptlang="javascript">var L3 = new Object();
 
L3.not = function(a) {
Line 2,726 ⟶ 3,081:
return L3.and(L3.ifThen(a, b), L3.ifThen(b, a));
}
</syntaxhighlight>
</lang>
… and try these:
<syntaxhighlight lang="text">
L3.not(true) // false
L3.not(var a) // undefined
Line 2,739 ⟶ 3,094:
 
L3.iff(a, 2 == 2) // undefined
</syntaxhighlight>
</lang>
Here is a compact solution
<syntaxhighlight lang="javascript">
trit = {false: 'F', maybe: 'U', true: 'T'}
nand = (a, b) => (a == trit.false || b == trit.false) ? trit.true : (a == trit.maybe || b == trit.maybe) ? trit.maybe : trit.false
not = (a) => nand(a, a)
and = (a, b) => not(nand(a, b))
or = (a, b) => nand(not(a), not(b))
nor = (a, b) => not(or(a, b))
implies = (a, b) => nand(a, not(b))
iff = (a, b) => or(and(a, b), nor(a, b))
xor = (a, b) => not(iff(a, b))
</syntaxhighlight>
... to test it
<syntaxhighlight lang="javascript">
functor = {nand, and, or, nor, implies, iff, xor}
display = {nand: '⊼', and: '∧', or: '∨', nor: '⊽', implies: '⇒', iff: '⇔', xor: '⊻', not: '¬'}
values = Object.values(trit)
 
log = 'NOT\n';
for (let a of values) log += `${display.not}${a} = ${a}\n`
 
log += '\nNAND AND OR NOR IMPLIES IFF XOR'
for (let a of values) {
for (let b of values) {
log += "\n"
for (let op in functor) log += `${a} ${display[op]} ${b} = ${functor[op](a, b)} `
}
}
console.log(log)
</syntaxhighlight>
...Output:
<syntaxhighlight lang="text">
NOT
¬F = F
¬U = U
¬T = T
 
NAND AND OR NOR IMPLIES IFF XOR
F ⊼ F = T F ∧ F = F F ∨ F = F F ⊽ F = T F ⇒ F = T F ⇔ F = T F ⊻ F = F
F ⊼ U = T F ∧ U = F F ∨ U = U F ⊽ U = U F ⇒ U = T F ⇔ U = U F ⊻ U = U
F ⊼ T = T F ∧ T = F F ∨ T = T F ⊽ T = F F ⇒ T = T F ⇔ T = F F ⊻ T = T
U ⊼ F = T U ∧ F = F U ∨ F = U U ⊽ F = U U ⇒ F = U U ⇔ F = U U ⊻ F = U
U ⊼ U = U U ∧ U = U U ∨ U = U U ⊽ U = U U ⇒ U = U U ⇔ U = U U ⊻ U = U
U ⊼ T = U U ∧ T = U U ∨ T = T U ⊽ T = F U ⇒ T = T U ⇔ T = U U ⊻ T = U
T ⊼ F = T T ∧ F = F T ∨ F = T T ⊽ F = F T ⇒ F = F T ⇔ F = F T ⊻ F = T
T ⊼ U = U T ∧ U = U T ∨ U = T T ⊽ U = F T ⇒ U = U T ⇔ U = U T ⊻ U = U
T ⊼ T = F T ∧ T = T T ∨ T = T T ⊽ T = F T ⇒ T = T T ⇔ T = T T ⊻ T = F
</syntaxhighlight>
 
=={{header|jq}}==
Line 2,745 ⟶ 3,148:
as the three values since ternary logic agrees with Boolean logic for true and false, and because jq prints these three values consistently.
 
For consistency, all the ternary logic operators are defined here with the prefix "ternary_", but such a prefix is only needed for "not", "and", and "or", as these are jq keywords. <langsyntaxhighlight lang="jq">def ternary_nand(a; b):
if a == false or b == false then true
elif a == "maybe" or b == "maybe" then "maybe"
Line 2,777 ⟶ 3,180:
display_equiv( (false, "maybe", true ); (false, "maybe", true) ),
"etc etc"
</syntaxhighlight>
</lang>
{{out}}
<pre>"false and false is false"
Line 2,803 ⟶ 3,206:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">@enum Trit False Maybe True
const trits = (False, Maybe, True)
 
Line 2,829 ⟶ 3,232:
for a in trits
println(join(@sprintf("%10s ≡ %5s is %5s", a, b, a ≡ b) for b in trits))
end</langsyntaxhighlight>
 
{{out}}
Line 2,856 ⟶ 3,259:
 
With Julia 1.0 and the new type <tt>missing</tt>, three-value logic is implemented by default
<langsyntaxhighlight lang="julia"># built-in: true, false and missing
 
using Printf
Line 2,887 ⟶ 3,290:
for (A, B) in Iterators.product(tril, tril)
@printf("%8s | %8s | %8s\n", A, B, A ⊃ B)
end</langsyntaxhighlight>
 
{{out}}
Line 2,939 ⟶ 3,342:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
enum class Trit {
Line 3,024 ⟶ 3,427:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,061 ⟶ 3,464:
=={{header|langur}}==
{{trans|Go}}
<syntaxhighlight lang="langur"># borrowing null for "maybe"
{{works with|langur|0.6.12}}
 
<lang langur># borrowing null for "maybe"
val .trSet = [false, null, true]
 
val .and = ffn given.a, .b: switch[and] .a, .b {
case true, null:
case null, true:
Line 3,073 ⟶ 3,474:
}
 
val .or = ffn given.a, .b: switch[and] .a, .b {
case false, null:
case null, false:
Line 3,080 ⟶ 3,481:
}
 
val .imply = ffn .a, .b: if(.a nor .b: not? .a; .b)
 
# formatting function for the result values
# replacing null with "maybe"
# using left alignment of 5 code points
val .F = ffn .r: $"\{{nn [.r, "maybe"]:-5}}"
 
writeln "a not a"
for .a in .trSet {
writeln $"\{{.a:.fn F;}} \({{not? .a:.fn F)}}"
}
 
Line 3,095 ⟶ 3,496:
for .a in .trSet {
for .b in .trSet {
writeln $"\{{.a:.fn F;}} \{{.b:.fn F;}} \{{.and(.a, .b):.fn F;}}"
}
}
Line 3,102 ⟶ 3,503:
for .a in .trSet {
for .b in .trSet {
writeln $"\{{.a:.fn F;}} \{{.b:.fn F;}} \{{.or(.a, .b):.fn F;}}"
}
}
Line 3,109 ⟶ 3,510:
for .a in .trSet {
for .b in .trSet {
writeln $"\{{.a:.fn F;}} \{{.b:.fn F;}} \{{.imply(.a, .b):.fn F;}}"
}
}
Line 3,116 ⟶ 3,517:
for .a in .trSet {
for .b in .trSet {
writeln $"\{{.a:.fn F;}} \{{.b:.fn F;}} \{{.a ==? .b:.fn F;}}"
}
}
}</lang>
</syntaxhighlight>
 
{{out}}
Line 3,171 ⟶ 3,573:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'ternary logic
'0 1 2
Line 3,242 ⟶ 3,644:
longName3$ = word$("False,Don't know,True", i+1, ",")
end function
</langsyntaxhighlight>
 
{{out}}
Line 3,268 ⟶ 3,670:
T ? ? T ? ?
T T T T T F
</pre>
 
=={{header|M2000 Interpreter}}==
 
<syntaxhighlight lang="m2000 interpreter">module Ternary_logic {
class trit {
private:
variant val
function copy() {
m=this
m.trit
=m
}
public:
enum ternary {
True="True"
Maybe="Maybe"
False="False"
}
function true() {
=.copy(.True)
}
function maybe() {
=.copy(.Maybe)
}
function false() {
=.copy(.False)
}
operator "==" (k as trit) {
push .val=k.val
}
operator "^^" (k as trit) {
select enum .val
case .True
.val<=k.val
case .False
.val<=.False
case else
if k.val=.False then .val<=.False else .val<=.Maybe
end select
}
operator "^|" (k as trit) {
select enum .val
case .True
.val<=k.val
case .False
.val<=.True
case else
if k.val=.True then .val<=.True else .val<=.Maybe
end select
}
operator "||" (k as trit) {
select enum .val
case .False
.val<=k.val
case .True
.val<=.True
case else
if k.val=.True then .val<=.True else .val<=.Maybe
end select
}
operator "~~" (k as trit) {
select enum .val
case .True
.val<=k.val
case .False
if k.val=.True then .val<=.False else.if k.val=.False then .val<=.True else .val<=k.val
case else
.val<=.Maybe
end select
}
operator unary {
select enum .val
case .True
.val<=.False
case .False
.val<=.True
end select
}
group value {
value {
link parent val to val
=val
}
}
module trit {
if empty or not isnum then
read s as .ternary=.Maybe
.val<=s
else.if isnum then
read what
if what then
.val<=.True
else
.val<=.False
end if
end if
}
}
function enum2array(t) {
m=each(t)
while m {data eval(m)}
=array([])
}
string out, nl={
}
q=trit()
m=trit()
k=enum2array(q.ternary)
out ="not a" + nl
a=each(k)
while a
q=trit(array(a))
z=-q
out +=" ternary_not "+(q.value) + " = " + (z.value) + nl
end while
out +="a and b" + nl
a=each(k)
while a
b=each(k)
while b
q=trit(array(a))
m=trit(array(b))
z=q ^^ m
out += " " + (q.value) + " ternary_and " + (m.value) + " = " + (z.value) + nl
end while
end while
out +="a or b" + nl
a=each(k)
while a
b=each(k)
while b
q=trit(array(a))
m=trit(array(b))
z=q || m
out += " " + (q.value) + " ternary_or " + (m.value) + " = " + (z.value) + nl
end while
end while
out +="if a then b" + nl
a=each(k)
while a
b=each(k)
while b
q=trit(array(a))
m=trit(array(b))
z=q ^| m
out += " if " + (q.value) + " then " + (m.value) + " = " + (z.value) + nl
end while
end while
out +="a is equivalent to b" + nl
a=each(k)
while a
b=each(k)
while b
q=trit(array(a))
m=trit(array(b))
z=q ~~ m
out += " "+(q.value) + " is equivalent to " + (m.value) + " = " + (z.value) + nl
end while
end while
report out
clipboard out
}
Ternary_logic
</syntaxhighlight>
{{out}}
<pre>not a
ternary_not True = False
ternary_not Maybe = Maybe
ternary_not False = True
a and b
True ternary_and True = True
True ternary_and Maybe = Maybe
True ternary_and False = False
Maybe ternary_and True = Maybe
Maybe ternary_and Maybe = Maybe
Maybe ternary_and False = False
False ternary_and True = False
False ternary_and Maybe = False
False ternary_and False = False
a or b
True ternary_or True = True
True ternary_or Maybe = True
True ternary_or False = True
Maybe ternary_or True = True
Maybe ternary_or Maybe = Maybe
Maybe ternary_or False = Maybe
False ternary_or True = True
False ternary_or Maybe = Maybe
False ternary_or False = False
if a then b
if True then True = True
if True then Maybe = Maybe
if True then False = False
if Maybe then True = True
if Maybe then Maybe = Maybe
if Maybe then False = Maybe
if False then True = True
if False then Maybe = True
if False then False = True
a is equivalent to b
True is equivalent to True = True
True is equivalent to Maybe = Maybe
True is equivalent to False = False
Maybe is equivalent to True = Maybe
Maybe is equivalent to Maybe = Maybe
Maybe is equivalent to False = Maybe
False is equivalent to True = False
False is equivalent to Maybe = Maybe
False is equivalent to False = True
</pre>
 
Line 3,275 ⟶ 3,887:
The following script generates all truth tables for Maple logical operations. Note that in addition to the usual built-in logical operators for '''not''', '''or''', '''and''', and '''xor''', Maple also has '''implies'''.
 
<langsyntaxhighlight Maplelang="maple">tv := [true, false, FAIL];
NotTable := Array(1..3, i->not tv[i] );
AndTable := Array(1..3, 1..3, (i,j)->tv[i] and tv[j] );
OrTable := Array(1..3, 1..3, (i,j)->tv[i] or tv[j] );
XorTable := Array(1..3, 1..3, (i,j)->tv[i] xor tv[j] );
ImpliesTable := Array(1..3, 1..3, (i,j)->tv[i] implies tv[j] );</langsyntaxhighlight>
 
{{Out}}
 
<langsyntaxhighlight Maplelang="maple">> tv := [true, false, FAIL];
tv := [true, false, FAIL]
 
Line 3,316 ⟶ 3,928:
ImpliesTable := [true true true]
[ ]
[true FAIL FAIL]</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Type definition is not allowed in Mathematica. We can just use the build-in symbols "True" and "False", and add a new symbol "Maybe".
<langsyntaxhighlight lang="mathematica">Maybe /: ! Maybe = Maybe;
Maybe /: (And | Or | Nand | Nor | Xor | Xnor | Implies | Equivalent)[Maybe, Maybe] = Maybe;</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="mathematica">trits = {True, Maybe, False};
Print@Grid[
ArrayFlatten[{{{{Not}}, {{Null}}}, {List /@ trits,
Line 3,331 ⟶ 3,943:
Null}}}, {{{Null}}, {trits}}, {List /@ trits,
Outer[operator, trits, trits]}}]], {operator, {And, Or, Nand,
Nor, Xor, Xnor, Implies, Equivalent}}]</langsyntaxhighlight>
{{out}}
<pre>Not
Line 3,337 ⟶ 3,949:
Maybe Maybe
False True
 
 
 
And
Line 3,345 ⟶ 3,955:
Maybe Maybe Maybe False
False False False False
 
 
 
Line 3,353 ⟶ 3,962:
Maybe True Maybe Maybe
False True Maybe False
 
 
 
Line 3,361 ⟶ 3,969:
Maybe Maybe Maybe True
False True True True
 
 
 
Line 3,369 ⟶ 3,976:
Maybe False Maybe Maybe
False False Maybe True
 
 
 
Line 3,377 ⟶ 3,983:
Maybe Maybe Maybe Maybe
False True Maybe False
 
 
 
Line 3,393 ⟶ 3,998:
Maybe True Maybe Maybe
False True True True
 
 
 
Line 3,400 ⟶ 4,004:
True True Maybe False
Maybe Maybe Maybe Maybe
False False Maybe True</pre>
 
</pre>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П0 Сx С/П ^ 1 + 3 * + 1
+ 3 x^y ИП0 <-> / [x] ^ ^ 3
/ [x] 3 * - 1 - С/П 1 5
6 3 3 БП 00 1 9 5 6 9
БП 00 1 5 9 2 9 БП 00 1
5 6 6 5 БП 00 /-/ ЗН С/П</langsyntaxhighlight>
 
<u>Instruction</u>:
Line 3,421 ⟶ 4,023:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type Trit* = enum ttrue, tmaybe, tfalse
 
proc `$`*(a: Trit): string =
Line 3,476 ⟶ 4,078:
echo "$# or $#: $#".format(op1, op2, op1 or op2)
echo "$# then $#: $#".format(op1, op2, op1.then op2)
echo "$# equiv $#: $#".format(op1, op2, op1.equiv op2)</langsyntaxhighlight>
{{out}}
<pre>Not T: F
Line 3,520 ⟶ 4,122:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">type trit = True | False | Maybe
 
let t_not = function
Line 3,563 ⟶ 4,165:
print t_imply "Then";
print t_eq "Equiv";
;;</langsyntaxhighlight>
 
{{out}}
Line 3,613 ⟶ 4,215:
=== Using a general binary -> ternary transform ===
Instead of writing all of the truth-tables by hand, we can construct a general binary -> ternary transform and apply it to any logical function we want:
<langsyntaxhighlight OCamllang="ocaml">type trit = True | False | Maybe
 
let to_bin = function True -> [true] | False -> [false] | Maybe -> [true;false]
Line 3,652 ⟶ 4,254:
table2 "or" t_or;;
table2 "equiv" t_equiv;;
table2 "implies" t_imply;;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,705 ⟶ 4,307:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
tritValues = .array~of(.trit~true, .trit~false, .trit~maybe)
tab = '09'x
Line 3,830 ⟶ 4,432:
else if self == .trit~maybe then return .trit~maybe
else return \other
</syntaxhighlight>
</lang>
 
<pre>
Line 3,884 ⟶ 4,486:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program TernaryLogic (output);
 
type
Line 3,974 ⟶ 4,576:
writeln('False ', terToStr(terEquals(terTrue,terFalse)), ' ', terToStr(terEquals(terMayBe,terFalse)), ' ', terToStr(terEquals(terFalse,terFalse)));
writeln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 4,006 ⟶ 4,608:
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use v5.36;
File <TT>Trit.pm</TT>:
<lang perl>package Trit;
 
package Trit;
# -1 = false ; 0 = maybe ; 1 = true
use List::Util qw(min max);
 
our @ISA = qw(Exporter);
use Exporter 'import';
our @EXPORT = qw(%E);
 
my %E = (true => 1, false => -1, maybe => 0);
our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe);
our %EXPORT_TAGS = (
all => \@EXPORT_OK,
const => [qw(TRUE FALSE MAYBE)],
bool => [qw(is_true is_false is_maybe)],
);
 
use List::Util qw(min max);
 
use overload
'<=>' => sub ($a,$b) { $_[0]a->clonecmp($b) },
'<=>cmp' => sub ($a,$b) { $_[0]a->cmp($_[1]b) },
'cmp==' => sub ($a,$b,$) { $_[0]->cmp($_[1])a == $$b },
'==eq' => sub { (${a,$_[0]}b,$) == ${ $a->equiv($_[1]}b) },
'eq>' => sub ($a,$b,$) { $_[0]-$a >equiv( $_[1])E{$b} },
'><' => sub ($a,$b,$) { ${$_[0]}a < > $E{$_[1]b} },
'<>=' => sub ($a,$b,$) { ${$_[0]}a <>= ${$_[1]}b },
'><=' => sub ($a,$b,$) { ${$_[0]}a ><= ${$_[1]}b },
'<=|' => sub { (${a,$_[0]}b,$,$,$) <={ ${a->or($_[1]}b) },
'|&' => sub ($a,$b,$,$,$) { $_[0]a->orand($_[1]b) },
'&!' => sub ($a,$,$) { $_[0]a->andnot($_[1]) },
'!~' => sub ($a,$,$,$,$) { $_[0]a->not() },
'~neg' => sub ($a,$,$) { $_[0]->not()$$a },
'""' => sub ($a,$,$) { $_[0]a->tostr() },
'0+' => sub ($a,$,$) { $_[0]a->tonum() },
;
 
sub neweqv ($a,$b) {
$$a == $E{maybe} || $E{$b} == $E{maybe} ? $E{maybe} : # either arg 'maybe', return 'maybe'
{
$$a == $E{false} && $E{$b} == $E{false} ? $E{true} : # both args 'false', return 'true'
my ($class, $v) = @_;
min $$a, $E{$b} # either arg 'false', return 'false', otherwise 'true'
my $ret =
!defined($v) ? 0 :
$v eq 'true' ? 1 :
$v eq 'false'? -1 :
$v eq 'maybe'? 0 :
$v > 0 ? 1 :
$v < 0 ? -1 :
0;
return bless \$ret, $class;
}
 
# do tests in a manner that avoids overloaded operators
sub TRUE() { new Trit( 1) }
sub FALSE() { new Trit(-1$class, $v) }{
my $value =
sub MAYBE() { new Trit( 0) }
! defined $v ? $E{maybe} :
 
$v =~ /true/ ? $E{true} :
sub clone
$v =~ /false/ ? $E{false} :
{
my $retv =~ /maybe/ ? $E{$_[0]maybe}; :
$v gt $E{maybe} ? $E{true} :
return bless \$ret, ref($_[0]);
$v lt $E{maybe} ? $E{false} :
$E{maybe} ;
bless \$value, $class;
}
 
sub tostr ($a) { ${$_[0]}a > 0$E{maybe} ? "'true"' : ${$_[0]}a < 0$E{maybe} ? "'false"' : "'maybe"' }
sub tonum ($a) { ${$_[0]}a }
 
sub is_truenot { ($a) {$_[0]} Trit->new( -$a 0) }
sub is_falsecmp { ($a,$b) { Trit->new( $_[0]}a <=> $b 0) }
sub is_maybeand { ($a,$b) { Trit->new( min $_[0]}a, ==$b 0) }
sub or ($a,$b) { Trit->new( max $a, $b ) }
sub equiv ($a,$b) { Trit->new( eqv $a, $b ) }
 
package main;
sub cmp { ${$_[0]} <=> ${$_[1]} }
Trit->import;
sub not { new Trit(-${$_[0]}) }
sub and { new Trit(min(${$_[0]}, ${$_[1]}) ) }
sub or { new Trit(max(${$_[0]}, ${$_[1]}) ) }
 
submy equiv@a {= new( Trit->new( $E{$_[0]true}), * Trit->new($E{$_[1]maybe} ), }</langTrit->new($E{false}) );
printf "Codes for logic values: %6s = %d %6s = %d %6s = %d\n", @a[0, 0, 1, 1, 2, 2];
File <TT>test.pl</TT>:
<lang perl>use Trit ':all';
 
# prefix ! (not) ['~' also can be used]
my @a = (TRUE(), MAYBE(), FALSE());
say "\na\tNOT a";
print "$_\t".(!$_)."\n" for @a;
 
# infix & (and)
print "\na\tNOT a\n";
say "\nAND\t" . join("\t",@a);
print "$_\t".(!$_)."\n" for @a; # Example of use of prefix operator NOT. Tilde ~ also can be used.
for my $a (@a) { print $a; print "\t" . ($a & $_) for @a; say '' }
 
# infix | (or)
say "\nOR\t" . join("\t",@a);
for my $a (@a) { print $a; print "\t" . ($a | $_) for @a; say '' }
 
# infix eq (equivalence)
print "\nAND\t".join("\t",@a)."\n";
forsay my"\nEQV\t" $a. join("\t",@a) {;
for my $a (@a) { print $a; print "\t" . ($a eq $_) for @a; say '' }
print $a;
for my $b (@a) {
print "\t".($a & $b); # Example of use of infix & (and)
}
print "\n";
}
 
# infix == (equality)
print "\nOR\t".join("\t",@a)."\n";
forsay my"\n==\t" $a. join("\t",@a) {;
for my $a (@a) { print $a; print "\t" . ($a == $_) for @a; say '' }</syntaxhighlight>
print $a;
{{out}}
for my $b (@a) {
<pre>Codes for logic values: true = 1 maybe = 0 false = -1
print "\t".($a | $b); # Example of use of infix | (or)
}
print "\n";
}
 
a NOT a
print "\nEQV\t".join("\t",@a)."\n";
for my $a (@a) {
print $a;
for my $b (@a) {
print "\t".($a eq $b); # Example of use of infix eq (equivalence)
}
print "\n";
}
 
print "\n==\t".join("\t",@a)."\n";
for my $a (@a) {
print $a;
for my $b (@a) {
print "\t".($a == $b); # Example of use of infix == (equality)
}
print "\n";
}</lang>
{{out}}
<pre>a NOT a
true false
maybe maybe
Line 4,149 ⟶ 4,719:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">enum</span> <span style="color: #000000;">T</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">M</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">F</span>
<span style="color: #008080;">type</span> <span style="color: #000000;">ternary</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">T</span><span style="color: #0000FF;">,</span><span style="color: #000000;">M</span><span style="color: #0000FF;">,</span><span style="color: #000000;">F</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">type</span>
Line 4,204 ⟶ 4,774:
<span style="color: #000000;">show_truth_table</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t_implies</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"imp"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show_truth_table</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t_equal</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"eq"</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,246 ⟶ 4,816:
=={{header|PHP}}==
Save the sample code as executable shell script on your *nix system:
<langsyntaxhighlight PHPlang="php">#!/usr/bin/php
<?php
 
Line 4,308 ⟶ 4,878:
}
 
</syntaxhighlight>
</lang>
Sample output:
<pre>--- Sample output for a equivalent b ---
Line 4,322 ⟶ 4,892:
for a=false and b=false a equivalent b is true
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
(show_op1('!') ; true),
nl,
foreach(Op in ['/\\','\\/','->','=='])
(show_op2(Op) ; nl,true)
end.
 
ternary(true,'!') = false.
ternary(maybe,'!') = maybe.
ternary(false,'!') = true.
 
ternary(Cond,'!') = Res =>
C1 = cond(Cond == maybe,maybe,cond(Cond,true,false)),
Res = ternary(C1,'!').
 
ternary(true,'/\\',A) = A.
ternary(maybe,'/\\',A) = cond(A==false,false,maybe).
ternary(false,'/\\',_A) = false.
 
ternary(true,'\\/',_A) = true.
ternary(maybe,'\\/',A) = cond(A==true,true, maybe).
ternary(false,'\\/',A) = A.
 
ternary(true,'->',A) = A.
ternary(maybe,'->',A) = cond(A==true,true,maybe).
ternary(false,'->',_) = true.
 
ternary(true,'==',A) = A.
ternary(maybe,'==',_) = maybe.
ternary(false,'==',A) = ternary(A,'!').
 
ternary(Cond1,Op,Cond2) = Res =>
C1 = cond(Cond1 == maybe,maybe,cond(Cond1,true,false)),
C2 = cond(Cond2 == maybe,maybe,cond(Cond2,true,false)),
Res = ternary(C1,Op,C2).
 
show_op1(Op) =>
println(Op),
println(['_' : _ in 1..11]),
foreach(V1 in [true,maybe,false])
V2 = ternary(V1,Op),
printf("%5w %5w \n",V1,V2)
end,
nl.
 
show_op2(Op) =>
Vs = [true,maybe,false],
printf("%2w %5w %5w %5w\n",Op,Vs[1],Vs[2],Vs[3]),
println(['_' : _ in 1..25]),
foreach(V1 in Vs)
printf("%-5w | ", V1),
foreach(V2 in Vs)
C = ternary(V1,Op,V2),
printf("%5w ",C)
end,
nl
end,
nl.</syntaxhighlight>
 
{{out}}
<pre>!
___________
true false
maybe maybe
false true
 
 
/\ true maybe false
_________________________
true | true maybe false
maybe | maybe maybe false
false | false false false
 
\/ true maybe false
_________________________
true | true true true
maybe | true maybe maybe
false | true maybe false
 
-> true maybe false
_________________________
true | true maybe false
maybe | true maybe maybe
false | true true true
 
== true maybe false
_________________________
true | true maybe false
maybe | maybe maybe maybe
false | false maybe true </pre>
 
===Simple examples===
<syntaxhighlight lang="picat">main =>
println(ternary(10 > 3,'->',maybe).ternary('!')),
println(ternary(4 < 18,'/\\',$not membchk('a',"picat")).ternary('->',maybe).ternary('==',true)).</syntaxhighlight>
 
{{out}}
<pre>maybe
true</pre>
 
=={{header|PicoLisp}}==
In addition for the standard T (for "true") and NIL (for "false") we define 0 (zero, for "maybe").
<langsyntaxhighlight PicoLisplang="picolisp">(de 3not (A)
(or (=0 A) (not A)) )
 
Line 4,349 ⟶ 5,020:
((=T A) B)
((=0 A) 0)
(T (3not B)) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(for X '(T 0 NIL)
(println 'not X '-> (3not X)) )
 
Line 4,357 ⟶ 5,028:
(for X '(T 0 NIL)
(for Y '(T 0 NIL)
(println X (car Fun) Y '-> ((cdr Fun) X Y)) ) ) )</langsyntaxhighlight>
{{out}}
<pre style="height:20em;overflow:scroll">not T -> NIL
not 0 -> 0
not NIL -> T
Line 4,398 ⟶ 5,069:
NIL equivalent 0 -> 0
NIL equivalent NIL -> T</pre>
 
=={{header|PureBasic}}==
{{trans|FreeBasic}}
<syntaxhighlight lang="purebasic">DataSection
TLogic:
Data.i -1,0,1
TSymb:
Data.s "F","?","T"
EndDataSection
 
Structure TL
F.i
M.i
T.i
EndStructure
 
Structure SYM
TS.s{2}[3]
EndStructure
 
*L.TL=?TLogic
*S.SYM=?TSymb
 
Procedure.i NOT3(*x.TL)
ProcedureReturn -*x
EndProcedure
 
Procedure.i AND3(*x.TL,*y.TL)
If *x>*y : ProcedureReturn *y : Else : ProcedureReturn *x : EndIf
EndProcedure
 
Procedure.i OR3(*x.TL,*y.TL)
If *x<*y : ProcedureReturn *y : Else : ProcedureReturn *x : EndIf
EndProcedure
 
Procedure.i EQV3(*x.TL,*y.TL)
ProcedureReturn *x * *y
EndProcedure
 
Procedure.i IMP3(*x.TL,*y.TL)
If -*y>*x : ProcedureReturn -*y : Else : ProcedureReturn *x : EndIf
EndProcedure
 
If OpenConsole("")
PrintN(" (AND) ( OR) (EQV) (IMP) (NOT)")
PrintN(" F ? T F ? T F ? T F ? T ")
PrintN(" -------------------------------------------------")
For *i.TL=*L\F To *L\T
rs$=" "+*S\TS[*i+1]+" | "
rs$+*S\TS[AND3(*L\F,*i)+1]+" "+*S\TS[AND3(*L\M,*i)+1]+" "+*S\TS[AND3(*L\T,*i)+1]
rs$+" "
rs$+*S\TS[OR3(*L\F,*i)+1] +" "+*S\TS[OR3(*L\M,*i)+1] +" "+*S\TS[OR3(*L\T,*i)+1]
rs$+" "
rs$+*S\TS[EQV3(*L\F,*i)+1]+" "+*S\TS[EQV3(*L\M,*i)+1]+" "+*S\TS[EQV3(*L\T,*i)+1]
rs$+" "
rs$+*S\TS[IMP3(*L\F,*i)+1]+" "+*S\TS[IMP3(*L\M,*i)+1]+" "+*S\TS[IMP3(*L\T,*i)+1]
rs$+" "+*S\TS[NOT3(*i)+1]
PrintN(rs$)
Next
EndIf
Input()</syntaxhighlight>
{{out}}
<pre> (AND) ( OR) (EQV) (IMP) (NOT)
F ? T F ? T F ? T F ? T
-------------------------------------------------
F | F F F F ? T T ? F T T T T
? | F ? ? ? ? T ? ? ? ? ? T ?
T | F ? T T T T F ? T F ? T F
</pre>
 
=={{header|Python}}==
In Python, the keywords 'and', 'not', and 'or' are coerced to always work as boolean operators. I have therefore overloaded the boolean bitwise operators &, |, ^ to provide the required functionality.
<langsyntaxhighlight lang="python">class Trit(int):
def __new__(cls, value):
if value == 'TRUE':
Line 4,529 ⟶ 5,269:
for b in values:
expr = '%s %s %s' % (a, op, b)
print(' %s = %s' % (expr, eval(expr)))</langsyntaxhighlight>
 
{{out}}
Line 4,581 ⟶ 5,321:
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery ">
<lang Quackery >
[ 2 ] is maybe ( --> t )
Line 4,686 ⟶ 5,426:
say " false | " false true t.<=> paddedtrit sp
say "| " false maybe t.<=> paddedtrit sp
say "| " false false t.<=> paddedtrit cr</langsyntaxhighlight>
 
'''Output:'''
Line 4,719 ⟶ 5,459:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang typed/racket
 
; to avoid the hassle of adding a maybe value that is as special as
Line 4,780 ⟶ 5,520:
(for*: : Void ([a (in-list '(true maybe false))]
[b (in-list '(true maybe false))])
(printf "~a ~a ~a = ~a~n" a (object-name proc) b (proc a b))))</langsyntaxhighlight>
 
{{out}}
Line 4,830 ⟶ 5,570:
The precedence of each operator is specified as equivalent to an existing operator. We've taken the liberty of using a double arrow for implication, to avoid confusing it with <tt>⊃</tt>, (U+2283 SUPERSET OF).
 
<syntaxhighlight lang="raku" perl6line># Implementation:
enum Trit <Foo Moo Too>;
 
Line 4,876 ⟶ 5,616:
Foo ∧ Too ∨ Foo ⇒ Foo ≡ Too,
Foo ∧ Too ∨ Too ⇒ Foo ≡ Foo,
);</langsyntaxhighlight>
 
{{out}}
Line 4,914 ⟶ 5,654:
{{Works with|Red|0.6.4}}
 
<langsyntaxhighlight Redlang="red">Red ["Ternary logic"]
 
; define trits as a set of 3 Red words: 'oui, 'non and 'bof
Line 4,966 ⟶ 5,706:
print rejoin [pad mold s 25 " " do s]
]
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,983 ⟶ 5,723:
=={{header|REXX}}==
This REXX program is a re-worked version of the REXX program used for the Rosetta Code task: &nbsp; ''truth table''.
<langsyntaxhighlight lang="rexx">/*REXX program displays a ternary truth table [true, false, maybe] for the variables */
/*──── and one or more expressions. */
/*──── Infix notation is supported with one character propositional constants. */
Line 5,178 ⟶ 5,918:
otherwise return -13 /*error, unknown function.*/
end /*select*/
</syntaxhighlight>
</lang>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here &nbsp; ──► &nbsp; [[CHANGESTR.REX]].
<br><br>
Line 5,255 ⟶ 5,995:
maybe maybe ────► maybe
</pre>
 
=={{header|RPL}}==
Ternary logic can be considered as a simplified version of Zadeh's fuzzy logic. In this paradigm, boolean values turn into floating-point ones going from 0 (completely false) to 1 (completely true):
AND(a,b), OR(a,b) and NOT(a) are resp. redefined as MIN(a,b), MAX(a,b) and (1-a). Other boolean operators can then be built by combining these 3 atoms. A specific word is also needed to display results as ternary constants instead of numbers.
{{works with|Halcyon Calc|4.2.7}}
≪ 2 * CEIL 1 + { ‘FALSE’ ‘MAYBE’ ‘TRUE’ } SWAP GET ≫ ''''TELL'''’ STO
≪ OR EVAL '''TELL''' ≫ ''''TAND'''’ STO
≪ AND EVAL '''TELL''' ≫ ''''TOR'''’ STO
≪ 1 SWAP - EVAL '''TELL''' ≫ ''''TNOT'''’ STO
≪ SWAP '''TNOT TOR''' EVAL '''TELL''' ≫ ''''TIMPLY'''’ STO
≪ DUP2 '''TNOT TAND''' ROT '''TNOT''' ROT '''TAND TOR''' EVAL '''TELL''' ≫ ''''TXOR'''’ STO
1 ''''TRUE'''' STO 0.5 ''''MAYBE'''' STO 0 ''''FALSE'''' STO
 
FALSE MAYBE '''TXOR'''
1: ‘TRUE’
Only the Soviets could understand such a logic...
 
=={{header|Ruby}}==
Line 5,262 ⟶ 6,018:
 
{{works with|Ruby|1.9}}
<langsyntaxhighlight lang="ruby"># trit.rb - ternary logic
# http://rosettacode.org/wiki/Ternary_logic
 
Line 5,346 ⟶ 6,102:
# false.trit == obj # => false, maybe or true
def trit; TritMagic; end
end</langsyntaxhighlight>
 
This IRB session shows ternary not, and, or, equal.
 
<langsyntaxhighlight lang="ruby">$ irb
irb(main):001:0> require './trit'
=> true
Line 5,366 ⟶ 6,122:
=> false
irb(main):008:0> false.trit == maybe
=> maybe</langsyntaxhighlight>
 
This program shows all 9 outcomes from <code>a.trit ^ b</code>.
 
<langsyntaxhighlight lang="ruby">require 'trit'
maybe = MAYBE
 
Line 5,377 ⟶ 6,133:
printf "%5s ^ %5s => %5s\n", a, b, a.trit ^ b
end
end</langsyntaxhighlight>
 
<pre>$ ruby -I. trit-xor.rb
Line 5,391 ⟶ 6,147:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">testFalse = 0 ' F
testDoNotKnow = 1 ' ?
testTrue = 2 ' T
Line 5,448 ⟶ 6,204:
function longName3$(i)
longName3$ = word$("False,Don't know,True", i+1, ",")
end function</langsyntaxhighlight><pre>Short and long names for ternary logic values
F False
? Don't know
Line 5,464 ⟶ 6,220:
=={{header|Rust}}==
{{trans|Kotlin}}
<langsyntaxhighlight Rustlang="rust">use std::{ops, fmt};
 
#[derive(Copy, Clone, Debug)]
Line 5,570 ⟶ 6,326:
println!();
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,604 ⟶ 6,360:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">sealed trait Trit { self =>
def nand(that:Trit):Trit=(this,that) match {
case (TFalse, _) => TTrue
Line 5,636 ⟶ 6,392:
println("\n- Equiv -")
for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a equiv b))
}</langsyntaxhighlight>
{{out}}
<pre>- NOT -
Line 5,706 ⟶ 6,462:
which use also short circuit evaluation.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: trit is new enum
Line 5,773 ⟶ 6,529:
end func;
 
$ syntax expr: .().xor.() is -> 15;
const func trit: (in trit: aTrit1) xor (in trit: aTrit2) is
return tritImplies[succ(ord(aTrit1))][succ(ord(aTrit2))];
Line 5,780 ⟶ 6,536:
return tritImplies[succ(ord(aTrit1))][succ(ord(aTrit2))];
 
syntax expr: .(). == .() is <-> 12;
const func trit: (in trit: aTrit1) == (in trit: aTrit2) is
return tritEquiv[succ(ord(aTrit1))][succ(ord(aTrit2))];
 
const func trit: rand (in trit: low, in trit: high) is
return trit conv (rand(ord(low), ord(high)));
 
# Begin of test code
Line 5,819 ⟶ 6,573:
writeTable(operand1 -> operand2, "->");
writeTable(operand1 == operand2, "==");
end func;</langsyntaxhighlight>
 
{{out}}
Line 5,857 ⟶ 6,611:
True | False Maybe True
</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "ternary_logic" )
@( description, "In logic, a three-valued logic (also trivalent, " )
@( description, "ternary, or trinary logic, sometimes abbreviated " )
@( description, "3VL) is any of several many-valued logic systems " )
@( description, "in which there are three truth values indicating " )
@( description, "true, false and some indeterminate third value. " )
@( see_also, "http://rosettacode.org/wiki/Ternary_logic" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure ternary_logic is
 
type ternary is (no, maybe, yes);
 
function ternary_and( left : ternary; right : ternary ) return ternary is
begin
if left < right then
return left;
else
return right;
end if;
end ternary_and;
 
function ternary_or( left : ternary; right : ternary ) return ternary is
begin
if left > right then
return left;
else
return right;
end if;
end ternary_or;
 
function ternary_not( right : ternary ) return ternary is
begin
case right is
when yes => return no;
when maybe => return maybe;
when no => return yes;
when others => put_line( "Unexpected value" );
end case;
end ternary_not;
 
function ternary_image( ternary_value : ternary ) return string is
begin
case ternary_value is
when yes => return "Yes";
when no => return "No";
when maybe => return "Maybe";
when others => put_line( "Unexpected value" );
end case;
end ternary_image;
 
begin
? "Ternary Not:"
@ "not no => " & ternary_image( ternary_not( no ) )
@ "not maybe => " & ternary_image( ternary_not( maybe ) )
@ "not yes => " & ternary_image( ternary_not( yes ) );
new_line;
 
? "Ternary And:"
@ "no and no => " & ternary_image( ternary_and( no, no ) )
@ "no and maybe => " & ternary_image( ternary_and( no, maybe ) )
@ "no and yes => " & ternary_image( ternary_and( no, yes ) )
@ "maybe and no => " & ternary_image( ternary_and( maybe, no ) )
@ "maybe and maybe => " & ternary_image( ternary_and( maybe, maybe ) )
@ "maybe and yes => " & ternary_image( ternary_and( maybe, yes ) )
@ "yes and no => " & ternary_image( ternary_and( yes, no ) )
@ "yes and maybe => " & ternary_image( ternary_and( yes, maybe ) )
@ "yes and yes => " & ternary_image( ternary_and( yes, yes ) );
new_line;
 
? "Ternary Or:"
@ "no or no => " & ternary_image( ternary_or( no, no ) )
@ "no or maybe => " & ternary_image( ternary_or( no, maybe ) )
@ "no or yes => " & ternary_image( ternary_or( no, yes ) )
@ "maybe or no => " & ternary_image( ternary_or( maybe, no ) )
@ "maybe or maybe => " & ternary_image( ternary_or( maybe, maybe ) )
@ "maybe or yes => " & ternary_image( ternary_or( maybe, yes ) )
@ "yes or no => " & ternary_image( ternary_or( yes, no ) )
@ "yes or maybe => " & ternary_image( ternary_or( yes, maybe ) )
@ "yes or yes => " & ternary_image( ternary_or( yes, yes ) );
new_line;
end ternary_logic;</syntaxhighlight>
{{out}}
<pre>
$ spar ternary_logic.sp
Ternary Not:
not no => Yes
not maybe => Maybe
not yes => No
 
Ternary And:
no and no => No
no and maybe => No
no and yes => No
maybe and no => No
maybe and maybe => Maybe
maybe and yes => Maybe
yes and no => No
yes and maybe => Maybe
yes and yes => Yes
 
Ternary Or:
no or no => No
no or maybe => Maybe
no or yes => Yes
maybe or no => Maybe
maybe or maybe => Maybe
maybe or yes => Yes
yes or no => Yes
yes or maybe => Yes
yes or yes => Yes</pre>
 
=={{header|Tcl}}==
The simplest way of doing this is by constructing the operations as truth tables. The code below uses an abbreviated form of truth table.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
namespace eval ternary {
# Code generator
Line 5,926 ⟶ 6,798:
* false
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">namespace import ternary::*
puts "x /\\ y == x \\/ y"
puts " x | y || result"
Line 5,937 ⟶ 6,809:
puts [format " %-5s | %-5s || %-5s" $x $y $z]
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,957 ⟶ 6,829:
=={{header|True BASIC}}==
{{trans|BASIC256}}
<langsyntaxhighlight lang="basic">
FUNCTION and3(a, b)
IF a < b then LET and3 = a else LET and3 = b
Line 6,024 ⟶ 6,896:
NEXT a
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,030 ⟶ 6,902:
</pre>
 
=={{header|V (Vlang)}}==
{{trans|AutoHotkey}}
Note:
 
1) V (Vlang) doesn't have a true "ternary" operator, but unlike in other languages, its "if-else if-else" can be written on a single line.
=={{header|Yabasic}}==
{{trans|BASIC256}}
<lang yabasic>
tFalse = 0
tDontKnow = 1
tTrue = 2
 
2) This "trick" can make code more understandable, where a traditional ternary style could be visually confusing.
sub and3(a,b)
if a < b then return a else return b : fi
end sub
 
3) Something like this, "a=1?b:a=0?1:a+b>1?1:0.5" is instead "if a == 1 {b} else if a == 0 {1} else if a + b > 1 {1} else {0.5}"
sub or3(a,b)
if a > b then return a else return b : fi
end sub
 
Below is an example of how this would look, which can be compared to traditional ternary usage:
sub eq3(a,b)
switch a
case tDontKnow or b = tDontKnow
return tDontKnow
case b
return tTrue
default
return tFalse
end switch
end sub
 
<syntaxhighlight lang="v (vlang)">import math
sub xor3(a,b)
return not3(eq3(a,b))
end sub
 
subfn not3main(b) {
aa := [1.0,0.5,0]
return 2-b
bb := [1.0,0.5,0]
end sub
mut res :=''
for a in aa {
res += '\tTernary_Not\t' + a.str() + '\t=\t' + ternary_not(a) + '\n'
}
res += '-------------\n'
for a in aa {
for b in bb {
res += a.str() + '\tTernary_And\t' + b.str() + '\t=\t' + ternary_and(a,b) + '\n'
}
}
res += '-------------\n'
for a in aa {
for b in bb {
res += a.str() + '\tTernary_or\t' + b.str() + '\t=\t' + ternary_or(a,b) + '\n'
}
}
res += '-------------\n'
for a in aa {
for b in bb {
res += a.str() + '\tTernary_then\t' + b.str() + '\t=\t' + ternary_if_then(a,b) + '\n'
}
}
res += '-------------\n'
for a in aa {
for b in bb {
res += a.str() + '\tTernary_equiv\t' + b.str() + '\t=\t' + ternary_equiv(a,b) + '\n'
}
}
res = res.replace('1.', 'true')
res = res.replace('0.5', 'maybe')
res = res.replace('0', 'false')
println(res)
}
 
fn ternary_not(a f64) string {
sub shortName3$(i)
return mid$math.abs("F?T", i+1, a-1).str()
}
end sub
 
fn ternary_and(a f64, b f64) string {
sub longName3$(i)
return if a < b {a.str()} else {b.str()}
switch i
}
case 1
return "Don't know"
case 2
return "True"
default
return "False"
end switch
end sub
 
fn ternary_or(a f64, b f64) string {
print "Nombres cortos y largos para valores logicos ternarios:"
return if a > b {a.str()} else {b.str()}
for i = tFalse to tTrue
}
print shortName3$(i), " ", longName3$(i)
next i
fn ternary_if_then(a f64, b f64) string {
print
return if a == 1 {b.str()} else if a == 0 {'1.'} else if a + b > 1 {'1.'} else {'0.5'}
}
fn ternary_equiv(a f64, b f64) string {
return if a == b {'1.'} else if a == 1 {b.str()} else if b == 1 {a.str()} else {'0.5'}
}</syntaxhighlight>
 
print "Funciones de parametro unico"
print "x", " ", "=x", " ", "not(x)"
for i = tFalse to tTrue
print shortName3$(i), " ", shortName3$(i), " ", shortName3$(not3(i))
next i
print
 
print "Funciones de doble parametro"
print "x"," ","y"," ","x AND y"," ","x OR y"," ","x EQ y"," ","x XOR y"
for a = tFalse to tTrue
for b = tFalse to tTrue
print shortName3$(a), " ", shortName3$(b), " ",
print shortName3$(and3(a,b)), " ", shortName3$(or3(a,b))," ",
print shortName3$(eq3(a,b)), " ", shortName3$(xor3(a,b))
next b
next a
end
</lang>
{{out}}
<pre>
Ternary_Not true = false
Igual que la entrada de Liberty BASIC.
Ternary_Not maybe = maybe
Ternary_Not false = true
-------------
true Ternary_And true = true
true Ternary_And maybe = maybe
true Ternary_And false = false
maybe Ternary_And true = maybe
maybe Ternary_And maybe = maybe
maybe Ternary_And false = false
false Ternary_And true = false
false Ternary_And maybe = false
false Ternary_And false = false
-------------
true Ternary_or true = true
true Ternary_or maybe = true
true Ternary_or false = true
maybe Ternary_or true = true
maybe Ternary_or maybe = maybe
maybe Ternary_or false = maybe
false Ternary_or true = true
false Ternary_or maybe = maybe
false Ternary_or false = false
-------------
true Ternary_then true = true
true Ternary_then maybe = maybe
true Ternary_then false = false
maybe Ternary_then true = true
maybe Ternary_then maybe = maybe
maybe Ternary_then false = maybe
false Ternary_then true = true
false Ternary_then maybe = true
false Ternary_then false = true
-------------
true Ternary_equiv true = true
true Ternary_equiv maybe = maybe
true Ternary_equiv false = false
maybe Ternary_equiv true = maybe
maybe Ternary_equiv maybe = true
maybe Ternary_equiv false = maybe
false Ternary_equiv true = false
false Ternary_equiv maybe = maybe
false Ternary_equiv false = true
</pre>
 
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var False = -1
var Maybe = 0
var True = 1
Line 6,173 ⟶ 7,088:
for (u in trits) System.write("%(t == u) ")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 6,206 ⟶ 7,121:
M | M M M
F | F M T
</pre>
 
=={{header|Yabasic}}==
{{trans|BASIC256}}
<syntaxhighlight lang="yabasic">
tFalse = 0
tDontKnow = 1
tTrue = 2
 
sub not3(b)
return 2-b
end sub
 
sub and3(a,b)
return min(a,b)
end sub
 
sub or3(a,b)
return max(a,b)
end sub
 
sub eq3(a,b)
if a = tDontKnow or b = tDontKnow then
return tDontKnow
elsif a = b then
return tTrue
else
return tFalse
end if
end sub
 
sub xor3(a,b)
return not3(eq3(a,b))
end sub
 
sub shortName3$(i)
return mid$("F?T", i+1, 1)
end sub
 
sub longName3$(i)
switch i
case 1
return "Don't know"
case 2
return "True"
default
return "False"
end switch
end sub
 
print "Nombres cortos y largos para valores logicos ternarios:"
for i = tFalse to tTrue
print shortName3$(i), " ", longName3$(i)
next i
print
 
print "Funciones de parametro unico"
print "x", " ", "=x", " ", "not(x)"
for i = tFalse to tTrue
print shortName3$(i), " ", shortName3$(i), " ", shortName3$(not3(i))
next i
print
 
print "Funciones de doble parametro"
print "x"," ","y"," ","x AND y"," ","x OR y"," ","x EQ y"," ","x XOR y"
for a = tFalse to tTrue
for b = tFalse to tTrue
print shortName3$(a), " ", shortName3$(b), " ";
print shortName3$(and3(a,b)), " ", shortName3$(or3(a,b)), " ";
print shortName3$(eq3(a,b)), " ", shortName3$(xor3(a,b))
next b
next a
end
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de Liberty BASIC.
</pre>
 
885

edits