Forums

Ternary Operator? (?:)

General discussion about Cobra. Releases and general news will also be posted here.
Feel free to ask questions or just say "Hello".

Ternary Operator? (?:)

Postby CodexArcanum » 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:
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?
CodexArcanum
 
Posts: 21

Re: Ternary Operator? (?:)

Postby Charles » Wed May 05, 2010 12:33 pm

We have it now:
plural = if(items.count==1, '', 's')
name = if(customer, customer.name, '(noname)') # assuming customer's type is Customer?

# the general form is:
if(CONDITION, TVALUE, FVALUE)

Only one of TVALUE or FVALUE is evaluated. The type is the greatest common denominator type between TVALUE and FVALUE.

It's called the "if expression". It uses the same keyword as the statement ("if") and it follows the same order (condition, truth part, false part).

See also the barely started reference manual which should really be subsumed into the wiki:

-- http://cobra-language.com/docs/manual/expressions/if.html
-- http://cobra-language.com/docs/manual/

Hmm, methinks that we need a How To on various kinds of expressions.

Regarding the scope of "example", that's correct. Cobra is more like Python and less like C# in the treatment of local variables. I call them "hassle free locals".
Charles
 
Posts: 2515
Location: Los Angeles, CA

Re: Ternary Operator? (?:)

Postby Charles » Wed May 05, 2010 12:49 pm

Rather than a How To, I think I'll do a wiki page called something like ExpressionTour.
Charles
 
Posts: 2515
Location: Los Angeles, CA

Re: Ternary Operator? (?:)

Postby Gameday » Wed May 05, 2010 1:04 pm

Looks nice. Gonna make use of it :)
Gameday
 
Posts: 27

Re: Ternary Operator? (?:)

Postby CodexArcanum » Wed May 05, 2010 2:19 pm

Oh! Too cool, that's really helpful. I think I actually ignored that page because I thought it was just discussing the regular "if statement" not a separate "if expression", :oops: though now that I see if I do like the syntax. Short and sweet.
CodexArcanum
 
Posts: 21


Return to Discussion

Who is online

Users browsing this forum: No registered users and 30 guests