问题描述
我正在使用DLR在C#中实现语言解释器,并且在使用三元运算符时遇到了一些麻烦.至此,我已经实现了基本的函数声明/调用,如下所示:
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
对于函数体是一系列表达式,我没有问题-总是返回最后一个表达式的值,而且我确保解释器中的所有情况至少返回 something 作为副作用.我现在正在尝试实现三元运算符(?:).我正在渲染的表达式树看起来像这样:
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);
其中trueExp和falseExp都是有效表达式.
where trueExp and falseExp are both valid expressions.
问题似乎是IfThenElse表达式未返回值,因此,基本上,即使trueExp和falseExp正在构建表达式树,IfThenElse表达式的最终结果始终为null.除了制作一个Runtime函数并显式调用它之外,还有没有办法使用DLR实现三元运算符? (即:是否执行IfThenElse并在true和false子句中返回实际值的表达式?)
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
但是现在,由于上述问题,当编译到程序中时,此方法始终返回null.
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!
推荐答案
Expression.IfThenElse
是if (...) ... else ...;
构造,而不是三元运算符.
Expression.IfThenElse
is an if (...) ... else ...;
construct, not the ternary operator.
三元运算符是 Expression.Condition
The ternary operator is Expression.Condition
这篇关于如何在DLR中实现三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!