|
| 1 | +###Conditional Expressions |
| 2 | + |
| 3 | +To express choosing between two alternatives, Scala has a conditional expression if-else |
| 4 | + |
| 5 | +It looks like a if-else in Java, but is used for expressions, not statements |
| 6 | + |
| 7 | +```def abs(x: Int) = if (x >= 0) x else -x``` |
| 8 | + |
| 9 | +x >=0 is a *predicate*, of type Boolean |
| 10 | + |
| 11 | +####Boolean expressions |
| 12 | + |
| 13 | +can be composed of |
| 14 | + |
| 15 | +> true false //Constants |
| 16 | +
|
| 17 | +> !b //Negation |
| 18 | +
|
| 19 | +> b && b //Conjunction |
| 20 | +
|
| 21 | +> b || b //Disjunction |
| 22 | +
|
| 23 | +####Rewrite rules for Booleans |
| 24 | +How do we define meaning for boolean expressions? Well, simply by giving rewrite rules, which give some template for boolean expressions on the left, and how to rewrite it on the right |
| 25 | + |
| 26 | +> !true --> false |
| 27 | +
|
| 28 | +>!false --> true |
| 29 | +
|
| 30 | +True and some other expression *e* will always give you the same as *e*; false and some other expression *e* will always give you false |
| 31 | +> true && e --> e |
| 32 | +
|
| 33 | +>false && e --> false |
| 34 | +
|
| 35 | +Rules for or are analogous for rules of and; they're the duals of those |
| 36 | +> true || e --> true |
| 37 | +> false || e --> e |
| 38 | +
|
| 39 | +Note that && and || do not always need their right operand to be evaluated; we say these expressions use short-circuit evaluation |
| 40 | + |
| 41 | +####Value Definitions |
| 42 | +We have seen that function parameters can be passed by value or be passed by name - the same distinction applies to definition. |
| 43 | + |
| 44 | +The ```def``` form is in a sense, call by name; it's right and side is evaluated on each use. |
| 45 | + |
| 46 | +There is also a ```val``` form, which is "by-value"; eg: |
| 47 | + |
| 48 | +```val x = 2``` |
| 49 | + |
| 50 | +```val y = square(x)``` |
| 51 | + |
| 52 | +The right hand side of a val definition is evaluated at the point of the definition itself. Afterwards, the name refers to the value - for instance, y above refers to 4, not to square(2). |
| 53 | + |
| 54 | +####Value Definitions and Termination |
| 55 | +The difference between the ```val``` and ```def``` forms becomes apparent when the right hand side doesn't terminate |
| 56 | + |
| 57 | +```def loop: Boolean = loop``` |
| 58 | + |
| 59 | +If we say ```def x = loop```, nothing happens - we just defined another name for loop. Whereas, if we define ```val x = loop```, we're caught in an infinite loop. |
0 commit comments