如何在 DLR 中实现三元运算符
我正在使用 DLR 在 C# 中实现语言解释器,但在使用三元运算符时遇到了一些问题。此时,我已经实现了基本的函数声明/调用,如下所示:
F := (x) -> x + 1
F(1) # returns 2
我没有遇到函数体是表达式序列的问题——总是返回最后一个表达式的值,并且我已经确保解释器中的所有情况都至少返回一些东西作为副作用。我现在正在尝试实现三元运算符(?:)。我正在渲染的表达式树如下所示:
work = Expression.IfThenElse(
Expression.IsTrue(Expression.Convert(work, typeof(Boolean))),
trueExp,
falseExp);
其中 trueExp 和 falseExp 都是有效表达式。
问题似乎是 IfThenElse 表达式不返回值,因此基本上即使 trueExp 和 falseExp 正在构建表达式树,IfThenElse 表达式的最终结果也始终为 null。除了创建运行时函数并显式调用它之外,是否有办法使用 DLR 实现三元运算符? (即:一个表达式。它执行 IfThenElse 并返回 true 和 false 子句中的实际值?)
我希望解析的是这样的:
F := (x) -> (x = 1) ? 4 : 5
F(1) #4
F(2) #5
但是现在,由于概述的问题,当编译到程序中时,它总是返回 null多于。
我将不胜感激任何帮助,这太令人烦恼了!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Expression.IfThenElse
是一个if (...) ... else ...;
构造,而不是三元运算符。三元运算符是
Expression.Condition
Expression.IfThenElse
is anif (...) ... else ...;
construct, not the ternary operator.The ternary operator is
Expression.Condition