How to Implement the Ternary Operator in the DLR
Asked Answered
D

1

6

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!

Diphenylamine answered 14/2, 2012 at 19:8 Comment(0)
D
20

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

The ternary operator is Expression.Condition

Debug answered 14/2, 2012 at 19:15 Comment(3)
Is it possible to emulate Expression.Condition with Expression.IfThenElse? i.e instead of return a ? b :c do ` if (as) return b else return c;`?Tricornered
@zespri: If all you want to do is return a value, sure. In that case they are the same. Obviously you can't use IfThenElse inside another expression though, since it's a statement. Personally I find return a ? b : c; more easy comprehend though.Debug
Fair enough, I'm just not sure how to do the "return" part in the IfThenElse approach then.Tricornered

© 2022 - 2024 — McMap. All rights reserved.