Note that there are some explanatory texts on larger screens.

plurals
  1. POCode Golf: Mathematical expression evaluator (that respects PEMDAS)
    text
    copied!<p>I challenge you to write a mathematical expression evaluator that respects PEMDAS (order of operations: parentheses, exponentiation, multiplication, division, addition, subtraction) without using regular expressions, a pre-existing "Eval()"-like function, a parsing library, etc.</p> <p>I saw one pre-existing evaluator challenge on SO (<a href="https://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions">here</a>), but that one specifically required left-to-right evaluation.</p> <p>Sample inputs and outputs:</p> <pre><code>"-1^(-3*4/-6)" -&gt; "1" "-2^(2^(4-1))" -&gt; "256" "2*6/4^2*4/3" -&gt; "1" </code></pre> <p>I wrote an evaluator in C#, but would like to see how badly it compares to those of smarter programmers in their languages of choice.</p> <h3>Related:</h3> <blockquote> <p><a href="https://stackoverflow.com/questions/928563/code-golf-evaluating-mathematical-expressions">Code Golf: Evaluating mathematical expressions</a></p> </blockquote> <p>Clarifications:</p> <ol> <li><p>Let's make this a function that accepts a string argument and returns a string result.</p></li> <li><p>As for why no regexes, well, that's to level the playing field. I think there ought to be a separate challenge for "the most compact regex".</p></li> <li><p>Using StrToFloat() is acceptable. By "parsing library" I meant to exclude such things as general-purpose grammar parsers, also to level the playing-field.</p></li> <li><p>Support floats.</p></li> <li><p>Support paretheses, exponentiation, and the four arithmetic operators.</p></li> <li><p>Give multiplication and division equal precedence.</p></li> <li><p>Give addition and subtraction equal precedence.</p></li> <li><p>For simplicity, you may assume all inputs are well-formed.</p></li> <li><p>I don't have a preference as to whether your function accepts such things as ".1" or "1e3" as valid numbers, but accepting them would earn you brownie points. ;)</p></li> <li><p>For divide-by-zero cases, you could perhaps return "NaN" (assuming you wish to implement error handling).</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload