Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Generate a truth table from input string

by moritz (Cardinal)
on May 13, 2008 at 14:58 UTC ( [id://686287]=note: print w/replies, xml ) Need Help??


in reply to Generate a truth table from input string

Ah well, what stops you?

You could of course look to cpan to see if there's anything that can help you.

If you want to parse the string yourself, take a look at RFC: Parsing with perl - Regexes and beyond and perhaps at Parse::RecDescent.

Evaluation should be pretty simple once you have a parse tree.

  • Comment on Re: Generate a truth table from input string

Replies are listed 'Best First'.
Re^2: Generate a truth table from input string
by tachyon-II (Chaplain) on May 13, 2008 at 15:35 UTC

    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

      $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;
Re^2: Generate a truth table from input string
by Anonymous Monk on May 13, 2008 at 15:07 UTC
    the problem that i am facing is, NOT is represented by both ! and ', variables could be !(A)+!(B)+!(C) or A'+B'+C', both mean the same. how do i do it?

      s/(\w+)'/!\1/g

      Rule One: Do not act incautiously when confronting a little bald wrinkly smiling man.
        or as use warnings; would say...
        \1 better written as $1

        and use diagnostics; would elaborate...

        (W syntax) Outside of patterns, backreferences live on as variable +s. The use of backslashes is grandfathered on the right-hand side of +a substitution, but stylistically it's better to use the variable fo +rm because other Perl programmers will expect it, and it works better + if there are more than 9 backreferences.
        Is (a+b)' disallowed?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (4)
As of 2024-04-24 20:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found