Arithmetic evaluation: Difference between revisions
Content added Content deleted
m (→{{header|Sidef}}: loop fix) |
m (→{{header|Sidef}}: modified code to work with Sidef 2.10) |
||
Line 4,675: | Line 4,675: | ||
} |
} |
||
var b = s.split('-'); |
|||
b.len == 3 |
|||
? (-1 * b[1].to_num - b[2].to_num) |
? (-1 * b[1].to_num - b[2].to_num) |
||
: |
: operate(s, '-'); |
||
} |
} |
||
Line 4,683: | Line 4,684: | ||
var reM = /\*/; |
var reM = /\*/; |
||
var reMD = %r |
var reMD = %r"(\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*)"; |
||
var reA = /\d\+/; |
var reA = /\d\+/; |
||
Line 4,690: | Line 4,691: | ||
var match; |
var match; |
||
while (match = s.match(reMD)) { |
while (match = s.match(reMD)) { |
||
var cap = match.cap[0]; |
|||
cap ~~ reM |
|||
? s.sub!(reMD, operate(cap, '*').to_s) |
|||
: s.sub!(reMD, operate(cap, '/').to_s); |
|||
} |
} |
||
while (match = s.match(reAS)) { |
while (match = s.match(reAS)) { |
||
var cap = match.cap[0]; |
|||
cap ~~ reA |
|||
? s.sub!(reAS, add(cap).to_s) |
|||
: s.sub!(reAS, subtract(cap).to_s); |
|||
} |
} |
||
return |
return s; |
||
} |
} |
||
Line 4,712: | Line 4,715: | ||
} |
} |
||
return |
return evalExp(s).to_num; |
||
} |
}</lang> |
||
Testing the function: |
Testing the function: |
||
<lang ruby>[ |
<lang ruby>[ |
||
['2+3' => 5], |
['2+3' => 5], |
||
['-4-3' => -7], |
['-4-3' => -7], |
||
['-+2+3/4' => -1.25], |
['-+2+3/4' => -1.25], |
||
['2*3-4' => 2], |
['2*3-4' => 2], |
||
['2*(3+4)+2/4' => 2/4 + 14], |
['2*(3+4)+2/4' => 2/4 + 14], |
||
['2*-3--4+-0.25' => -2.25], |
['2*-3--4+-0.25' => -2.25], |
||
['2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10' => 7000], |
['2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10' => 7000], |
||
].each { |arr| |
].each { |arr| |
||
var (expr, res) = arr...; |
var (expr, res) = arr...; |
||
var num = |
var num = evalArithmeticExp(expr); |
||
num == res || ( |
|||
"Error occurred on expression '#{expr}': got '#{num}' instead of '#{res}'\n" |
die "Error occurred on expression '#{expr}': got '#{num}' instead of '#{res}'\n"; |
||
); |
); |
||