Question

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!

Was it helpful?

Solution

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

The ternary operator is Expression.Condition

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top