Ternary Operator? (?:)
Posted: Wed May 05, 2010 11:23 am
I may just be missing it, but I don't think Cobra has a ternary operator or a construct to replace it. It's a pretty common idiom in C#, and Python recently added one as well.
The C# version might go like:
The python one is similar in function but formatted different:
That one kind of implies that ValueC is the default and ValueD is a backup.
Cobra may already do something like that, but I haven't seen it. I know you can do a two-line if-else using commas, like:
(Oddly enough, you don't even have to declare example first. It appears to "leak" out of the if-else scope and be available afterwards).
But I think the one-liner isn't possible.
Would that be a worthwhile addition to the language, and if so which format to go with?
The C# version might go like:
- Code: Select all
var example = a < b ? ValueC : ValueD
The python one is similar in function but formatted different:
- Code: Select all
var example = ValueC if a < b else ValueD
That one kind of implies that ValueC is the default and ValueD is a backup.
Cobra may already do something like that, but I haven't seen it. I know you can do a two-line if-else using commas, like:
- Code: Select all
if a < b, example = ValueC
else, example = ValueD
(Oddly enough, you don't even have to declare example first. It appears to "leak" out of the if-else scope and be available afterwards).
But I think the one-liner isn't possible.
Would that be a worthwhile addition to the language, and if so which format to go with?