GNOME Bugzilla – Bug 687709
[Genie] Add support for Python ternary operator
Last modified: 2018-05-22 14:35:44 UTC
Python: a if test else b Genie: test ? a : b Let's make Genie more Pythonesque!
Patches welcome to fix this. Marking as enhancement
Such Python's approach have a restriction to one "if" part + non "else" part. That Genie's approach, that you suggest seems very implicit. Maybe it would be better to make: Like in Nim: a = if x > 8: 9 elif x < 4: 8 else: 10 But it seems to be not very clear. We could try to add extra spaces (but it's not good way): a = if x > 8: 9 elif x < 4: 8 else: 10 Lots of that ":" symbols... Not very clear again. Maybe we could to think to make it more clear: a = 3 if x > 4 else 4 if x > 3 else 5 if x < 0 Adding extra spaces will make it better: a = 3 if x > 4 else 4 if x > 3 else 5 if x < 0 Or so: a = 3 if x > 4 or 4 if x < 3 or 5 if x == 5 But I think, that better of all will be: a = 3 if x > 4 else 4 if x > 3 else 5 if x < 0 It's the most clear and it looks very similar to Genie's if-else if-else statements.
While I like the Python style it doesn't read that well as English. I think the Scala syntax is clearer in that respect and would fit well with Genie's if () else style. So two examples would be: var c = if (test) a else b response:string = if (log_in_successful) "Welcome!" else "The details supplied were not accepted." For details on the Scala syntax and I think a relevant comment on keeping it simple see: http://docs.scala-lang.org/style/control-structures.html#trivial-conditionals In terms of implementation then this would use the Vala ConditionalExpression object in the AST ( https://git.gnome.org/browse/vala/tree/vala/valaconditionalexpression.vala ). So it would not be practical to include "else if" in the syntax. That's beside the design argument that using "else if" makes it too complex and so inelegant. There probably needs to be further refactoring of the expression parsing in Genie if TokenType.IF is to be recognised in expressions. See https://bugzilla.gnome.org/show_bug.cgi?id=746704 for how TokenType.DEF was used for lambda expressions. Finally it may be worth considering the null-coalescing operator along with this ( https://bugzilla.gnome.org/show_bug.cgi?id=620133 ). The syntax could be: var c = a else b So if a has a value (i.e. not null) c = a otherwise the default is b. The point is TokenType.ELSE would also need to be recognised in an expression.
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/vala/issues/332.