Hacker News new | ask | show | jobs
by reycharles 3254 days ago
I find that the problem with the ternary operator isn't the operator itself per se, but the concrete syntax. If you could write it

    result = if boolean_flag
        then do_this()
        else do_that();
then I'm sure no one would find it as bad as they do now. The way you formatted the ternary with line-breaks helps a lot, too, I think!
4 comments

Block-oriented languages can do it; Rust, for example:

  let result = if boolean_flag {
      do_this()
  } else {
      do_that()
  };
Rust actually doesn’t have a ternary operator.
What do you mean "block-oriented"? I'd say this is part of Rust's ML heritage, and comes of being expression-oriented: if is just an expression, and evaluates to a value like any other expression.
Maybe "block oriented" is supposed to mean "has blocks that are expressions".
Sorry, “expression-oriented” was what I meant to write.
Just hopping on the bandwagon to point out that R can do it too, since everything in R is an expression:

    z <- if (x > y) 5 else 7
And of course this is trivial in Lisp:

    (setf z (> x y) 5 7)
You lost an "if" there :). setf will complain on trying to set 5 to 7.

What you meant is:

  (setf z (if (> x y) 5 7))
A nicer thing that I like about Lisp's "everything is an expression" is something that is considered as code smell by some:

  (setf foo (or var (compute-default-value) +some-default-constant+))
This works in Common Lisp, where the only value considered logically false is NIL, because or will short-circuit (as expected), returning not T, but the value of the first logically true result.

So e.g.

  (let ((a nil) (b 2) (c :foo))
    (or a b c))
returns 2.
Julia can do this as well:

    result = if boolean_flag do_this(); else do_that(); end
Though it does have the ternary ?: operator too.
Or Python:

    result = do_this() if boolean_flag else do_that()
I tend to like ternary operators and similar operations but the way python handles it really bothers me, I think because it essentially overloads the `if` keyword, and totally violates the if-then-else norm of conditional statements (ternary operator included). then-if-else is stranger than a do-while loop, but at least there's an occasional reason to use a do-while loop.
It bothers me a little, as well. I tend to think of it as a special type of comprehension, since it follows that format as opposed to the standard if statement.