Re: math formula substitution and evaluation



Daniel D Jones schreef:

Given something like the following:

my @variables = [3, 7, 13, 4, 12];
my @tests = ("2*a+b==c", "c-d+a==e");

I need to be able to evaluate the mathematical truth of the tests

#!/usr/bin/perl
# beware: this approach is wrong

use warnings;
use strict;

my $rv = qr~[-+]?(?:[0-9]+|[a-z]+)~ ; # value
my $ro = qr~(?:[-+*/^]|\*\*)~ ; # operator
my $re = qr~\A $rv(?:$ro$rv)* == $rv \z~x ;

my @v = <DATA> =~ /(\d+)/g ;
print join(', ', @v), "\n" ;

while ( <DATA> )
{
chomp ;
tr/A-Z/a-z/ ;
print "$_\t" ;
unless (/$re/) { print "ERROR\n" ; next }

s/([a-z])/($v[ord($1) - ord('a')])/g ;
print "$_\t", eval() ? 'T' : 'F', "\n" ;
}

__DATA__
3, 7, 13, 4, 12
2*a+b==c
c-d+a==e
c-d+a==a
c-d+a==ee
c-d++a==e
-D+c+a==E
2**a==8
2^a==8

--
Affijn, Ruud

"Gewoon is een tijger."


.



Relevant Pages