Reputation: 5644
I have started to implement DDMathParser
in my current project and I use this framework to calculate the results of formulas in combination with variables given in a dictionary (variable substitution).
Would it be possible to use something like if
statements in the formulas, e.g. "if ($a > 0) { $b / $c } else {$b * 1000}
?
I assume that if
statements could be created in a similar way than new functions (as described in the DDMathParser Wiki). If this would be the case, I would be glad if someone could show me how to do this.
Any ideas or hints on how to use if
statements in DDMathParser
?
Thank you!
Upvotes: 0
Views: 267
Reputation: 243156
DDMathParser
author here...
This isn't really possible, but not for the reason you think. DDMathParser
can parse if
just fine. It's the curly braces it would have issues with. You could maybe do:
if ($a > 0) ($b / $c) else ($b * 1000)
This would be parsed as:
if($a > 0) * ($b / $c) * else($b *1000)
Which is NSLogged
as:
multiply(multiply(if(l_gt($a,0)),divide($b,$c)),else(multiply($b,1000)))
So, you could do it, but it would be a total pain to try and handle the scoping yourself. I think it'd probably be easier to pre-parse the string into various parts:
if ($a > 0) => if(l_get($a, 0))
($b / $c) => divide($b, $c)
($b * 1000) => multiply($b, 1000)
And then handle that yourself.
Upvotes: 1