I have heard few talks on modern programming languages like scala (and few other languages whose names I cannot remember right now), and often got the sense of excitement when the speakers were talking like: "if is an expression in our programming language, it returns value, WOW". So the question is, why an when if
being an expression rather than a statement like in C
is better?
Why "if as expression not statement" is cool?
364 views Asked by exebook At
2
There are 2 answers
0
On
It may be surprising for some, but there are languages that don't have "statements" at all. One example would be Haskell. In such circumstances there is no choice than having if
expressions.
Note that any decent imperative language has if
expressions, too. It's just called and written differently, like, for example:
cond ? "yes" : "no"
Incidentally, imperative languages short circuit such an expression, which is slang for lazy evaluation of the 2nd and 3rd expression (just like Haskell does it anyway).
It has to do with dealing with values instead of dealing with (re)assignments. Values are simple and (re)assignments are hard; Consider java where if construct is a statement, and also blocks {} are also sort of statements, and try is also kind of statement, and neither of them could return value:
compare with scala, where all those statements are actually expressions and can return values:
Now I argue that scala version is plainly simpler for understanding)))
someObject
is value so it got assigned one time, and I'm not bothered that somewhere below it got reassigned. I don't have to move variables outsideif
andtry
blocks just to keep them visible to the outside. And if I have a lot of nested if blocks, I still can deduce what result value will be at each level just by looking at it, while in java I need to keep whole method, and in fact execute it in my head to be able to deduce what top level variables got updated and when. BTW java has?: operator
but it is very limited compared to scala's if expression (mainly because you can't use brakets within).