DDMathParser: Parsing formulas which contain if statements

☆樱花仙子☆ 提交于 2019-12-13 06:04:51

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/13935508/ddmathparser-parsing-formulas-which-contain-if-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!