6 ms·
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
by reycharles 9y 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!
- chrismorgan 9y agoBlock-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.
- lmm 9y agoWhat 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.
- nerdponx 9y agoMaybe "block oriented" is supposed to mean "has blocks that are expressions".
- deleted 9y ago[deleted]
- chrismorgan 9y agoSorry, “expression-oriented” was what I meant to write.
- 1wd 9y agoOr Python: result = do_this() if boolean_flag else do_that()
- jrkatz 9y agoI 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.
- JoBrad 9y agoIt 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.
- photon-torpedo 9y agoJulia can do this as well: result = if boolean_flag do_this(); else do_that(); end Though it does have the ternary ?: operator too.
- nerdponx 9y agoJust 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)
- TeMPOraL 9y agoYou 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.