Ternary logic: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 95:
=={{header|Action!}}==
<
DEFINE FALSE="0"
DEFINE MAYBE="1"
Line 192:
OD
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Ternary_logic.png Screenshot from Atari 8-bit computer]
Line 224:
We first specify a package "Logic" for three-valued logic. Observe that predefined Boolean functions, "and" "or" and "not" are overloaded:
<
type Ternary is (True, Unknown, False);
Line 238:
function To_Ternary(B: Boolean) return Ternary;
function Image(Value: Ternary) return Character;
end Logic;</
Next, the implementation of the package:
<
-- type Ternary is (True, Unknown, False);
Line 303:
end Implies;
end Logic;</
Finally, a sample program:
<
procedure Test_Tri_Logic is
Line 340:
Truth_Table(F => Equivalent'Access, Name => "Eq");
Truth_Table(F => Implies'Access, Name => "Implies");
end Test_Tri_Logic;</
{{out}}
Line 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'''
<
INT trit width = 1, trit base = 3;
Line 464:
#true # (false, maybe, true )
)[@-1,@-1][INITINT a, INITINT b]
);</
<
OP & = (LOGICAL a,b)LOGICAL: a AND b;
Line 489:
OP ~ = (LOGICAL a)LOGICAL: NOT a,
~= = (LOGICAL a,b)LOGICAL: a /= b; SCALAR!
FI#</
<
# -*- coding: utf-8 -*- #
Line 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)</
{{out}}
<pre>
Line 622:
Arturo's '':logical'' values inherently support ternary logic (<code>true</code>, <code>false</code> and <code>maybe</code>) and the corresponding logical operations.
<
loop vals 'v -> print ["NOT" v "=>" not? v]
Line 639:
loop vals 'v2
-> print [v1 "XOR" v2 "=>" xor? v1 v2]
]</
{{out}}
Line 679:
=={{header|AutoHotkey}}==
<
SetFormat, Float, 2.1
return Abs(a-1)
Line 698:
Ternary_Equiv(a,b){
return a=b?1:a=1?b:b=1?a:0.5
}</
Examples:<
bb:=[1,0.5,0]
Line 729:
StringReplace, Res, Res, 0, false, all
MsgBox % Res
return</
{{out}}
<pre> Ternary_Not true = false
Line 778:
=={{header|BASIC256}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="lb">
global tFalse, tDontKnow, tTrue
tFalse = 0
Line 849:
end case
end function
</syntaxhighlight>
{{out}}
<pre>
Line 857:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
REM Create a ternary class:
Line 902:
PRINT "TRUE EQV TRUE = " FN(mytrit.teqv)("TRUE","TRUE")
PROC_discard(mytrit{})</
{{out}}
<pre>
Line 937:
=={{header|C}}==
===Implementing logic using lookup tables===
<
typedef enum {
Line 1,007:
return 0;
}</
{{out}}
Line 1,055:
===Using functions===
<
typedef enum { t_F = -1, t_M, t_T } trit;
Line 1,090:
return 0;
}</
{{out}}
<pre>[Not]
Line 1,131:
the result is randomly sampled to true or false according to the chance.
(This description is definitely very confusing perhaps).
<
#include <stdlib.h>
Line 1,185:
return 0;
}</
=={{header|C sharp|C#}}==
<
/// <summary>
Line 1,232:
}
}
}</
{{out}}
<pre>¬True = False
Line 1,276:
=={{header|C++}}==
Essentially the same logic as the [[#Using functions|Using functions]] implementation above, but using class-based encapsulation and overridden operators.
<
#include <stdlib.h>
Line 1,349:
show_op(==);
return EXIT_SUCCESS;
}</
{{out}}
<pre>! ----
Line 1,381:
=={{header|Common Lisp}}==
<
(defun tri-and (&rest x) (apply #'* x))
(defun tri-or (&rest x) (tri-not (apply #'* (mapcar #'tri-not x))))
Line 1,411:
(print-table #'tri-or "OR")
(print-table #'tri-imply "IMPLY")
(print-table #'tri-eq "EQUAL")</
{{out}}
<pre>NOT:
Line 1,448:
=={{header|D}}==
Partial translation of a C entry:
<
struct Trit {
Line 1,515:
showOperation!"=="("Equiv");
showOperation!"==>"("Imply");
}</
{{out}}
<pre>[Not]
Line 1,558:
=={{header|Delphi}}==
<
interface
Line 1,613:
end;
end.</
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
<
and defining a set of constants implementing the above tables:
<
tvl_not: array[TriBool] = (tbTrue, tbMaybe, tbFalse);
tvl_and: array[TriBool, TriBool] = (
Line 1,642:
(tbFalse, tbMaybe, tbTrue),
);
</syntaxhighlight>
That's no real fun, but lookup can then be done with
<
=={{header|Elena}}==
ELENA 5.0 :
<
import system'routines;
import system'collections;
Line 1,717:
}
}
}</
{{out}}
<pre>
Line 1,762:
=={{header|Erlang}}==
<
-module(ternary).
-export([main/0, nott/1, andd/2,orr/2, then/2, equiv/2]).
Line 1,836:
io: format("~s\n", [B])
end.
</syntaxhighlight>
=={{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''.
<
! http://rosettacode.org/wiki/Ternary_logic
USING: combinators kernel ;
Line 1,881:
{ m [ >trit drop m ] }
{ f [ tnot ] }
} case ;</
Example use:
<
( scratchpad ) trits [ tnot ] map .
{ f m t }
Line 1,894:
{ { 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 } }</
Line 1,902:
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.
<
: tnot dup maybe <> if invert then ;
Line 1,935:
CR ." [IMPLY]" ' timply table2. CR
CR ." [EQUIV]" ' tequiv table2. CR
</syntaxhighlight>
{{out}}
Line 1,995:
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">
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Mon May 20 23:05:46
Line 2,093:
end program ternaryLogic
</syntaxhighlight>
=={{header|Free Pascal}}==
Line 2,099:
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
<
unit ternarylogic;
Line 2,165:
end;
end.
</syntaxhighlight>
<
{$mode objfpc}
uses
Line 2,211:
writeln('F|',tFalse >< tTrue:7, tFalse >< tMaybe:7,tFalse >< tFalse:7);
writeln;
end.</
<pre>
Output:
Line 2,251:
=={{header|FreeBASIC}}==
<
F=-1, M=0, T=1
end enum
Line 2,295:
outstr += " " + symbol(not(i))
print outstr
next i</
<pre>
(AND) ( OR) (EQV) (IMP) (NOT)
Line 2,321:
=={{header|Go}}==
Go has four operators for the bool type: ==, &&, ||, and !.
<
import "fmt"
Line 2,395:
}
}
}</
{{out}}
<pre>
Line 2,439:
=={{header|Groovy}}==
Solution:
<
TRUE, MAYBE, FALSE
Line 2,456:
Trit imply(Trit that) { this.nand(that.not()) }
Trit equiv(Trit that) { this.and(that).or(this.nor(that)) }
}</
Test:
<
Trit.values().each { b -> printf ('%6s', b) }
println '\n ----- ----- -----'
Line 2,498:
Trit.values().each { b -> printf ('%6s', a.equiv(b)) }
println()
}</
{{out}}
Line 2,538:
All operations given in terms of NAND, the functionally-complete operation.
<
main = mapM_ (putStrLn . unlines . map unwords)
Line 2,574:
where header = map (:[]) (take ((length $ head xs) - 1) ['A'..]) ++ [name]
pad s = s ++ replicate (5 - length s) ' '</
{{out}}
Line 2,634:
<
$define FALSE -1
$define UNKNOWN 0
Line 2,695:
procedure xor3(a,b) #: xor of two trits or error if invalid
return not3(eq3(a,b))
end</
{{libheader|Icon Programming Library}}
Line 2,746:
maybe: 0.5
<
and=: <.
or =: >.
if =: (>. -.)"0~
eq =: (<.&-. >. <.)"0</
Example use:
<
1 0.5 0
Line 2,775:
1 0.5 0
0.5 0.5 0.5
0 0.5 1</
Note that this implementation is a special case of "[[wp:fuzzy logic|fuzzy logic]]" (using a limited set of values).
Line 2,783:
Note that we might instead define values between 0 and 1 to represent independent probabilities:
<
and=: *
or=: *&.-.
if =: (or -.)"0~
eq =: (*&-. or *)"0</
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):
<
1 0.5 0
Line 2,812:
1 0.5 0
0.5 0.4375 0.5
0 0.5 1</
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:
<
or=: +.</
And, the boolean result tables would look like this:
<
0 0 0
0 0.5 1
Line 2,829:
0 0.5 1
0.5 0.5 0.5
1 0.5 1</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
public static enum Trit{
TRUE, MAYBE, FALSE;
Line 2,900:
}
}
}</
{{out}}
<pre>not TRUE: FALSE
Line 2,918:
Let's use the trit already available in JavaScript:
true, false (both boolean) and undefined…
<
L3.not = function(a) {
Line 2,951:
return L3.and(L3.ifThen(a, b), L3.ifThen(b, a));
}
</syntaxhighlight>
… and try these:
<syntaxhighlight lang="text">
L3.not(true) // false
L3.not(var a) // undefined
Line 2,964:
L3.iff(a, 2 == 2) // undefined
</syntaxhighlight>
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
Line 2,976:
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: '¬'}
Line 2,994:
}
console.log(log)
</syntaxhighlight>
...Output:
<syntaxhighlight lang="text">
NOT
¬F = F
Line 3,012:
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 3,018:
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. <
if a == false or b == false then true
elif a == "maybe" or b == "maybe" then "maybe"
Line 3,050:
display_equiv( (false, "maybe", true ); (false, "maybe", true) ),
"etc etc"
</syntaxhighlight>
{{out}}
<pre>"false and false is false"
Line 3,076:
{{works with|Julia|0.6}}
<
const trits = (False, Maybe, True)
Line 3,102:
for a in trits
println(join(@sprintf("%10s ≡ %5s is %5s", a, b, a ≡ b) for b in trits))
end</
{{out}}
Line 3,129:
With Julia 1.0 and the new type <tt>missing</tt>, three-value logic is implemented by default
<
using Printf
Line 3,160:
for (A, B) in Iterators.product(tril, tril)
@printf("%8s | %8s | %8s\n", A, B, A ⊃ B)
end</
{{out}}
Line 3,212:
=={{header|Kotlin}}==
<
enum class Trit {
Line 3,297:
println()
}
}</
{{out}}
Line 3,336:
{{works with|langur|0.6.12}}
<
val .trSet = [false, null, true]
Line 3,391:
writeln $"\.a:.F; \.b:.F; \.a ==? .b:.F;"
}
}</
{{out}}
Line 3,444:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'ternary logic
'0 1 2
Line 3,515:
longName3$ = word$("False,Don't know,True", i+1, ",")
end function
</
{{out}}
Line 3,548:
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'''.
<
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] );</
{{Out}}
<
tv := [true, false, FAIL]
Line 3,589:
ImpliesTable := [true true true]
[ ]
[true FAIL FAIL]</
=={{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".
<
Maybe /: (And | Or | Nand | Nor | Xor | Xnor | Implies | Equivalent)[Maybe, Maybe] = Maybe;</
Example:
<
Print@Grid[
ArrayFlatten[{{{{Not}}, {{Null}}}, {List /@ trits,
Line 3,604:
Null}}}, {{{Null}}, {trits}}, {List /@ trits,
Outer[operator, trits, trits]}}]], {operator, {And, Or, Nand,
Nor, Xor, Xnor, Implies, Equivalent}}]</
{{out}}
<pre>Not
Line 3,668:
=={{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 /-/ ЗН С/П</
<u>Instruction</u>:
Line 3,684:
=={{header|Nim}}==
<
proc `$`*(a: Trit): string =
Line 3,739:
echo "$# or $#: $#".format(op1, op2, op1 or op2)
echo "$# then $#: $#".format(op1, op2, op1.then op2)
echo "$# equiv $#: $#".format(op1, op2, op1.equiv op2)</
{{out}}
<pre>Not T: F
Line 3,783:
=={{header|OCaml}}==
<
let t_not = function
Line 3,826:
print t_imply "Then";
print t_eq "Equiv";
;;</
{{out}}
Line 3,876:
=== 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:
<
let to_bin = function True -> [true] | False -> [false] | Maybe -> [true;false]
Line 3,915:
table2 "or" t_or;;
table2 "equiv" t_equiv;;
table2 "implies" t_imply;;</
{{out}}
<pre>
Line 3,968:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
tritValues = .array~of(.trit~true, .trit~false, .trit~maybe)
tab = '09'x
Line 4,093:
else if self == .trit~maybe then return .trit~maybe
else return \other
</syntaxhighlight>
<pre>
Line 4,147:
=={{header|Pascal}}==
<
type
Line 4,237:
writeln('False ', terToStr(terEquals(terTrue,terFalse)), ' ', terToStr(terEquals(terMayBe,terFalse)), ' ', terToStr(terEquals(terFalse,terFalse)));
writeln;
end.</
{{out}}
<pre>
Line 4,270:
=={{header|Perl}}==
File <TT>Trit.pm</TT>:
<
# -1 = false ; 0 = maybe ; 1 = true
Line 4,339:
sub or { new Trit(max(${$_[0]}, ${$_[1]}) ) }
sub equiv { new Trit( ${$_[0]} * ${$_[1]} ) }</
File <TT>test.pl</TT>:
<
my @a = (TRUE(), MAYBE(), FALSE());
Line 4,383:
}
print "\n";
}</
{{out}}
<pre>a NOT a
Line 4,412:
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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,467:
<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>
<!--</
{{out}}
<pre>
Line 4,509:
=={{header|PHP}}==
Save the sample code as executable shell script on your *nix system:
<
<?php
Line 4,571:
}
</syntaxhighlight>
Sample output:
<pre>--- Sample output for a equivalent b ---
Line 4,587:
=={{header|Picat}}==
<
(show_op1('!') ; true),
nl,
Line 4,644:
nl
end,
nl.</
{{out}}
Line 4,679:
===Simple examples===
<
println(ternary(10 > 3,'->',maybe).ternary('!')),
println(ternary(4 < 18,'/\\',$not membchk('a',"picat")).ternary('->',maybe).ternary('==',true)).</
{{out}}
Line 4,689:
=={{header|PicoLisp}}==
In addition for the standard T (for "true") and NIL (for "false") we define 0 (zero, for "maybe").
<
(or (=0 A) (not A)) )
Line 4,713:
((=T A) B)
((=0 A) 0)
(T (3not B)) ) )</
Test:
<
(println 'not X '-> (3not X)) )
Line 4,721:
(for X '(T 0 NIL)
(for Y '(T 0 NIL)
(println X (car Fun) Y '-> ((cdr Fun) X Y)) ) ) )</
{{out}}
<pre>not T -> NIL
Line 4,765:
=={{header|PureBasic}}==
{{trans|FreeBasic}}
<
TLogic:
Data.i -1,0,1
Line 4,822:
Next
EndIf
Input()</
{{out}}
<pre> (AND) ( OR) (EQV) (IMP) (NOT)
Line 4,834:
=={{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.
<
def __new__(cls, value):
if value == 'TRUE':
Line 4,962:
for b in values:
expr = '%s %s %s' % (a, op, b)
print(' %s = %s' % (expr, eval(expr)))</
{{out}}
Line 5,014:
=={{header|Quackery}}==
<syntaxhighlight lang="quackery ">
[ 2 ] is maybe ( --> t )
Line 5,119:
say " false | " false true t.<=> paddedtrit sp
say "| " false maybe t.<=> paddedtrit sp
say "| " false false t.<=> paddedtrit cr</
'''Output:'''
Line 5,152:
=={{header|Racket}}==
<
; to avoid the hassle of adding a maybe value that is as special as
Line 5,213:
(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))))</
{{out}}
Line 5,263:
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"
enum Trit <Foo Moo Too>;
Line 5,309:
Foo ∧ Too ∨ Foo ⇒ Foo ≡ Too,
Foo ∧ Too ∨ Too ⇒ Foo ≡ Foo,
);</
{{out}}
Line 5,347:
{{Works with|Red|0.6.4}}
<
; define trits as a set of 3 Red words: 'oui, 'non and 'bof
Line 5,399:
print rejoin [pad mold s 25 " " do s]
]
</syntaxhighlight>
{{out}}
Line 5,416:
=={{header|REXX}}==
This REXX program is a re-worked version of the REXX program used for the Rosetta Code task: ''truth table''.
<
/*──── and one or more expressions. */
/*──── Infix notation is supported with one character propositional constants. */
Line 5,611:
otherwise return -13 /*error, unknown function.*/
end /*select*/
</syntaxhighlight>
Some older REXXes don't have a '''changestr''' BIF, so one is included here ──► [[CHANGESTR.REX]].
<br><br>
Line 5,695:
{{works with|Ruby|1.9}}
<
# http://rosettacode.org/wiki/Ternary_logic
Line 5,779:
# false.trit == obj # => false, maybe or true
def trit; TritMagic; end
end</
This IRB session shows ternary not, and, or, equal.
<
irb(main):001:0> require './trit'
=> true
Line 5,799:
=> false
irb(main):008:0> false.trit == maybe
=> maybe</
This program shows all 9 outcomes from <code>a.trit ^ b</code>.
<
maybe = MAYBE
Line 5,810:
printf "%5s ^ %5s => %5s\n", a, b, a.trit ^ b
end
end</
<pre>$ ruby -I. trit-xor.rb
Line 5,824:
=={{header|Run BASIC}}==
<
testDoNotKnow = 1 ' ?
testTrue = 2 ' T
Line 5,881:
function longName3$(i)
longName3$ = word$("False,Don't know,True", i+1, ",")
end function</
F False
? Don't know
Line 5,897:
=={{header|Rust}}==
{{trans|Kotlin}}
<
#[derive(Copy, Clone, Debug)]
Line 6,003:
println!();
}
}</
{{out}}
Line 6,037:
=={{header|Scala}}==
<
def nand(that:Trit):Trit=(this,that) match {
case (TFalse, _) => TTrue
Line 6,069:
println("\n- Equiv -")
for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a equiv b))
}</
{{out}}
<pre>- NOT -
Line 6,139:
which use also short circuit evaluation.
<
const type: trit is new enum
Line 6,252:
writeTable(operand1 -> operand2, "->");
writeTable(operand1 == operand2, "==");
end func;</
{{out}}
Line 6,293:
=={{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.
<
namespace eval ternary {
# Code generator
Line 6,359:
* false
}
}</
Demonstrating:
<
puts "x /\\ y == x \\/ y"
puts " x | y || result"
Line 6,370:
puts [format " %-5s | %-5s || %-5s" $x $y $z]
}
}</
{{out}}
<pre>
Line 6,390:
=={{header|True BASIC}}==
{{trans|BASIC256}}
<
FUNCTION and3(a, b)
IF a < b then LET and3 = a else LET and3 = b
Line 6,457:
NEXT a
END
</syntaxhighlight>
{{out}}
<pre>
Line 6,475:
Below is an example of how this would look, which can be compared to traditional ternary usage:
<
fn main() {
Line 6,537:
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'}
}</
{{out}}
Line 6,587:
=={{header|Wren}}==
<
var Maybe = 0
var True = 1
Line 6,649:
for (u in trits) System.write("%(t == u) ")
System.print()
}</
{{out}}
Line 6,686:
=={{header|Yabasic}}==
{{trans|BASIC256}}
<
tFalse = 0
tDontKnow = 1
Line 6,755:
next a
end
</syntaxhighlight>
{{out}}
<pre>
|