Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement the Ternary Operator in the DLR

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!

like image 720
Gakidou Avatar asked Feb 14 '12 19:02

Gakidou


1 Answers

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

The ternary operator is Expression.Condition

like image 59
Matti Virkkunen Avatar answered Sep 27 '22 23:09

Matti Virkkunen