Arithmetic evaluation: Difference between revisions

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

edits