How to Implement the Ternary Operator in the DLR

五迷三道 提交于 2019-12-07 04:16:46

问题


I am implementing a language interpreter in C# using the DLR, and I'm having some troubles with the ternary operator. At this point, I have basic function declarations/calls implemented, like so:

F := (x) -> x + 1
F(1)   # returns 2

I've not had a problem with a function body being a sequence of expressions -- the value of the last expression is always returned, and I've made sure all cases in the interpreter return at least something as a side effect. I'm now trying to implement the ternary operator (? :). The Expression tree I'm rendering looks like this:

work = Expression.IfThenElse(                                   
    Expression.IsTrue(Expression.Convert(work, typeof(Boolean))), 
    trueExp, 
    falseExp);

where trueExp and falseExp are both valid expressions.

The problem seems to be that the IfThenElse expression does not return a value, so basically even though trueExp and falseExp are building expression trees, the end result of the IfThenElse expression is always null. Short of making a Runtime function and explicitly calling it, is there a way to implement the ternary operator using the DLR? (ie: an Expression. that does the IfThenElse and returns the actual values in the true and false clauses?)

What I hope to parse is something like:

F := (x) -> (x = 1) ? 4 : 5
F(1)   #4
F(2)   #5

But right now this always returns null when compiled into a program, because of the problem outlined above.

I'd appreciate any help, this is quite vexing!


回答1:


Expression.IfThenElse is an if (...) ... else ...; construct, not the ternary operator.

The ternary operator is Expression.Condition



来源:https://stackoverflow.com/questions/9282703/how-to-implement-the-ternary-operator-in-the-dlr

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