Ternary logic: Difference between revisions
→{{header|Perl}}: Use modern Perl, avoid hard-coded values, be more careful in testing logic.
SqrtNegInf (talk | contribs) (→{{header|Perl}}: Use modern Perl, avoid hard-coded values, be more careful in testing logic.) |
|||
Line 4,479:
=={{header|Perl}}==
▲<syntaxhighlight lang="perl">use strict;
package Trit;
use List::Util qw(min max);▼
our @ISA = qw(Exporter);
our @EXPORT = qw(
my %E = (true => 1, false => -1, maybe => 0);
▲use List::Util qw(min max);
use overload
'<=>'
'
'
'
'
'
'
'
'
'
'
'
'
'""' => sub ($a,$,$) { $
'0+' => sub ($a,$,$) { $
;
sub
$$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 $ret =▼
min $$a, $E{$b} # either arg 'false', return 'false', otherwise 'true'
!defined($v) ? 0 :▼
$v eq 'true' ? 1 :▼
$v eq 'maybe'? 0 :▼
$v > 0 ? 1 :▼
$v < 0 ? -1 :▼
return bless \$ret, $class;▼
}
# do tests in a manner that avoids overloaded operators
sub
$E{maybe} ;
}
sub tostr ($a) { $
sub tonum ($a) { $
sub
sub
sub and
sub or
sub equiv ($a,$b) { Trit->new( eqv $a, $b ) }
package main;
Trit->import;
my @a = (
printf "Codes for logic values: %6s = %d %6s = %d %6s = %d\n", @a[0, 0, 1, 1, 2, 2];
# prefix ! (not) ['~' also can be used]
say "
print "$_\t".(!$_)."\n" for @a;
Line 4,555 ⟶ 4,550:
# infix | (or)
say "\nOR\t" . join("\t",@a);
for my $a (@a) { print $a; print "\t" . ($a | $_) for @a; say '' }
# infix eq (equivalence)
say "\nEQV\t" . join("\t",@a);
for my $a (@a) { print $a; print "\t" . ($a eq $_) for @a; say '' }
# infix == (equality)
say "\n==\t" . join("\t",@a);
for my $a (@a) { print $a; print "\t" . ($a == $_) for @a; say '' }</syntaxhighlight>
{{out}}
<pre>Codes for logic values: true = 1 maybe = 0 false = -1
<pre>a NOT a▼
true false
maybe maybe
|