Control Flow
Ordered Guards
Check ordered conditions from general to specific.
ordered-guards
Ordered guards let later checks refine an earlier result when the conditions are simple and explicit.
Ordered Guards
NestedGuards.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val score = 82
var result = "retry"
if (score >= 60) {
result = "pass"
}
if (score >= 90) {
result = "honor"
}
println("score=" + score)
println("result=" + result)
}
}
object Main {
def main(args: Array[String]): Unit = {
val score = 58
var result = "retry"
if (score >= 60) {
result = "pass"
}
if (score >= 90) {
result = "honor"
}
println("score=" + score)
println("result=" + result)
}
}
object Main {
def main(args: Array[String]): Unit = {
val score = 95
var result = "retry"
if (score >= 60) {
result = "pass"
}
if (score >= 90) {
result = "honor"
}
println("score=" + score)
println("result=" + result)
}
}
score ← 82, result ← retry
1object Main {2 def main(args: Array[String]): Unit = {3 val score→ 82 = 82 //@score=58, 954 var result→ retry = "retry"56 if (score >= 60) {result ← pass
6if (score82 >= 60) {7 result→ pass = "pass"8}9if (score >= 90) {println("score=" + score)
13 println("score=" + score82)14 println("result=" + resultpass)15 }16}outputscore=82 result=pass
score ← 58, result ← retry
1object Main {2 def main(args: Array[String]): Unit = {3 val score→ 58 = 584 var result→ retry = "retry"56 if (score >= 60) {7 result = "pass"8 }9 if (score >= 90) {10 result = "honor"11 }1213 println("score=" + score58)14 println("result=" + resultretry)15 }16}outputscore=58 result=retry
score ← 95, result ← retry
1object Main {2 def main(args: Array[String]): Unit = {3 val score→ 95 = 954 var result→ retry = "retry"56 if (score >= 60) {result ← pass
6if (score95 >= 60) {7 result→ pass = "pass"8}9if (score >= 90) {result ← honor
8}9if (score95 >= 90) {10 result→ honor = "honor"11}println("score=" + score)
13 println("score=" + score95)14 println("result=" + resulthonor)15 }16}outputscore=95 result=honor
Follow the Guards
scorestarts at82.resultstarts as"retry".- The
score >= 60check is true, soresultbecomes"pass". - The
score >= 90check is false, soresultstays"pass". - The program prints
score=82andresult=pass. | score |score >= 60|score >= 90| final result | | --- | --- | --- | --- | | 58 | false | false | retry | | 82 | true | false | pass | | 95 | true | true | honor |
Exercise: NestedGuards.scala
Reproduce result=pass for score 82, then try score 58 and score 95 and predict the final result.