]>
Dogcows Code - chaz/p5-Acme-Test-LogicalEquivalence/blob - lib/Acme/Test/LogicalEquivalence.pm
1 package Acme
::Test
::LogicalEquivalence
;
2 # ABSTRACT: Test if expressions are logically equivalent
9 our $VERSION = '0.001'; # VERSION
11 use Exporter
qw(import);
13 use namespace
::clean
-except
=> [qw(import)];
15 our @EXPORT_OK = qw(is_logically_equivalent);
18 sub is_logically_equivalent
{
25 for (my $i = 0; $i < 2 ** $numvars; ++$i) {
26 my @vars = split(//, substr(unpack("B32", pack('N', $i)), -$numvars));
28 (local $a, local $b) = @vars;
29 my $r1 = !!$sub1->(@vars);
31 (local $a, local $b) = @vars;
32 my $r2 = !!$sub2->(@vars);
34 my $test = !($r1 xor $r2);
36 my $args = join(', ', map { $_ ? 'T' : 'F' } @vars);
37 ok
($test, "expr1($args) <=> expr2($args)");
39 $equivalence = '' if !$test;
55 Acme::Test::LogicalEquivalence - Test if expressions are logically equivalent
64 use Acme::Test::LogicalEquivalence qw(is_logically_equivalent);
66 # test two expressions with 2 variables using the special vars $a and $b
67 is_logically_equivalent(2, sub { $a && $b }, sub { $b && $a });
70 is_logically_equivalent(2, sub { $_[0] && $_[1] }, sub { $_[1] && $_[0] });
72 # you can do as many vars as you like
73 is_logically_equivalent(3, sub { $_[0] || ($_[1] && $_[2]) },
74 sub { ($_[0] || $_[1]) && ($_[0] || $_[2]) });
80 Some expressions are "logically equivalent" to other expressions, but it may not be easy to tell if
81 one or both of the expressions are reasonably complicated. Or maybe you're like many other people
82 and are too lazy to go through the effort... Either way, why not let your computer prove logical
87 =head2 is_logically_equivalent
89 Test logical equivalence of two subroutines.
91 my $is_equivalent = is_logically_equivalent($numvars, &sub1, &sub2);
93 This will execute both of the subroutines one or more times (depending on how many variables you
94 specify) with different inputs. The subroutines shall be considered logically equivalent if, for all
95 combinations of inputs, they both return the same thing.
97 Returns true if the subroutines are logically equivalent, false otherwise.
105 What is logical equivalence? Start here: L<https://en.wikipedia.org/wiki/Logical_equivalence>
111 Charles McGarvey <chazmcgarvey@brokenzipper.com>
113 =head1 COPYRIGHT AND LICENSE
115 This software is copyright (c) 2016 by Charles McGarvey.
117 This is free software; you can redistribute it and/or modify it under
118 the same terms as the Perl 5 programming language system itself.
This page took 0.042936 seconds and 4 git commands to generate.