Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Generate a truth table from input string

by tachyon-II (Chaplain)
on May 13, 2008 at 15:35 UTC ( [id://686302]=note: print w/replies, xml ) Need Help??


in reply to Re: Generate a truth table from input string
in thread Generate a truth table from input string

Parsing is quite possibly not required. Assuming that the variables can be assumed to contain a true value why not just leverage perl.

$str =~ s/\*/&&/g; $str =~ s/\+/||/g; # $str =~ s/'/!/g; $str =~ s/(\w+)'/!$1/g; $str =~ s/\(([^\)]+)\)'/!($1)/g; $str =~ s/\w+/1/g; my $truth = eval $str;

If the a/b/A/B vars have associated values all that is required is to substitute them in. Perl does the parsing and calculates the truth.

Update

Modified to deal with ' postfix syntax

Replies are listed 'Best First'.
Re^3: Generate a truth table from input string
by ikegami (Patriarch) on May 13, 2008 at 16:43 UTC
    $str =~ s/'/!/g;
    is not sufficient to convert a postfix operator to a prefix operator. "a'" produces the invalid code "1!".
      $str =~ s/(\w+)'/!$1/g; $str =~ s/\(([^\)]+)\)'/!($1)/g;

        It you're going to allow (a+b)' — the OP might be happy with only supporting /\w+'/ — you must allow (a*(b+c))' too.

        Other than that, there are a few other problems. You don't handle xor, you assume the same precedence and associativity as Perl, and you don't generate a truth table. I presume that's intentional and that you're leaving those as an exercise to the reader, so I'm just documenting what's left to do.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://686302]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (None)
    As of 2024-04-25 01:31 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found