Re:Show HN: A pure C89 implementation of Go channels, with b...
by IlliOnato on Thursday December 14, 2023 @07:14AM
(#38640535)
I would say that languages where "if" can be used as expression provide a different (perhaps better) syntax for the same ternary operator.
a = if x then y else z
is just a more verbose version of a = x ? y : z;
Raku uses yet another form of the same operator: a = x ?? y :: z;
Syntactic sugar :-)
Re:Show HN: A pure C89 implementation of Go channels, with b...
by lizmat on Thursday December 14, 2023 @07:53AM
(#38640785)
It's actually
a = x ?? y !! z
And that's because a single : is used for many other semantics in the Raku Programming Language. And ?? and !! standout better in code.
Re:Show HN: A pure C89 implementation of Go channels, with b...
by IlliOnato on Thursday December 14, 2023 @08:11AM
(#38640933)
You are right, of course. Sorry! "Colon belongs to Larry" :-)
I think I made this mistake because :: was used in one of the drafts for Perl 6, but the final specification uses !!
Re:Show HN: A pure C89 implementation of Go channels, with b...
by 8372049 on Thursday December 14, 2023 @09:28AM
(#38641680)
Sorry for the confusion, but you did indeed decipher my meaning (if-statements)! I agree that if-expressions are far more readable in languages that support them (Python and Haskell come to mind for me), even though they're arguably just syntactic sugar for the ternary operator.
For example, the following F# code (you can run `dotnet fsi` in a terminal to try it out, if you have dotnet installed) is equivalent to a ternary expression:
// the value of x is "is_not_lower" after evaluation (x is a constant/immutable value, just like a 'const' value in JS) let x = if 0 > 1 then "is_lower" else "is_not_lower"
Which is equivalent to the following (in JS): const x = 0 > 1 ? "is_lower" : "is_not_lower"
In F# (and also Kotlin which I linked before), you can have clean code with if-elif-else ladders while the equivalent (using nested ternaries) would be hard to read. For example:
// the constant/immutable variable "comparison" is either "HIGHER", "LOWER" or "EQUAL" depending on the branch taken let comparison = if a > b then "HIGHER" elif a < b then "LOWER" else "EQUAL"
In JS land (and also most common programming languages which have plain if-statements), I agree a ternary would often be preferrable as long as it's not nested.