Hacker News new | ask | show | jobs
by 3eb7988a1663 5 hours ago
Never will I understand ternary operators. As soon as you introduce it, some chuckle heads want to use them everywhere. Worse if the syntax allows nested ternarys. I guess it keeps the language open for code golfing, but it otherwise seems like redundant syntax that at best saves a few characters.
4 comments

That’s why “if” should just be an expression
This is the best answer in my opinion. Ternary is just sugar for an expressive if. LuaJIT seems to be focusing on adding new syntax though, maintainer might not be amenable to updating existing semantics.
I don't think if-expressions have to affect existing semantics. Basically, in the parser you would have two different kinds of AST nodes, one for when the `if` keyword is encountered in statement position and another for when it's encountered in expression position.

Right now, `if` in expression position is just a syntax error ("unexpected symbol")

Well, I believe there could be some complications with parsing related to the fact that Lua grammar doesn't really requires semicolons between the statements.

But other than that, yeah, detecting "if" in the expression position is pretty unambiguous. No idea why most languages went with "cond-expr ? then-expr : else-expr" bracketed syntax instead.

Surely the most likely explanation is familiary from C?

But e.g. ml-family languages (like OCaml, F#, Haskell) and Rust just have the *if* expression that has a non-void value. If your language accepts expressions as statements (most do?), then I think that should just be compatible out of the box.

Yes, but why C had that syntax? Oh, right, because it didn't use if-then[-else]-end for the conditional statement, and reusing if(cond)[-else] with prohibited braces would be awkward.

Oh, and Lua most famously does not accept expressions as statements. Which, now that I think of it, would actually evade most of the parsing complications.

Yep. Everything should be.
Lua basically already has ternary operators anyway since "and" and "or" short circuit. I also don't see the need of adding additional syntax for it.

  local x = condition ? value_a : value b
  local x = condition and value_a or value_b
> The classic Lua idiom a and b or c has a pitfall when b is nil or false: then c is returned, even when a is truthy.

> E.g. true and false or 42 returns 42, whereas true ? false : 42 returns the (expected) false.

I guess for the JS case it makes sense to be able to shave a few characters for file shrinking purposes, but generally I'm more biased to code clarity and "self-explainability"
That’s what compression is for.
I find it most useful in languages that have non-mutable variables and you want to avoid a mutable variable or an extra function when the value comes from a simple condition.