Skip to content

Latest commit

 

History

History
112 lines (79 loc) · 6.69 KB

File metadata and controls

112 lines (79 loc) · 6.69 KB

Built-in Control Structures

Scala has only few built-in control structures: if, while, for, try, match, and function calls. Instead it encourages you to define your own control abstractions using functions: high-order functions. In the next session covering functions you will learn how to do this.

While Loops

While loops are shortly described in the Scala specification and have this syntax:

while <condition> <body>

As you know from other languages a while loop executes the body as long as the condition is fulfilled (true) from 0 to x times. The body will not be executed at all in case the first condition check leads to false.

In the worksheet there are two while loop exercises.

Both cases work with a counter as a condition until a certain limit is reached. Looking at the second loop you can see that in the body there is an if condition making sure only even numbers are printed.

[Quiz] Do you figure out how to remove the if condition and have it check in the while condition? https://gist.github.com/taitruong/9507910

[Answer] Remember in the last session about using braces? https://gist.github.com/taitruong/9507992

As you can see you can surround several lines of code using braces. In Scala a required expression is evaluated and used at the end.

This code is for its purpose okay. But it is not clean. If you want to put a code block in the while condition then it may make sense to separate the concerns: https://gist.github.com/taitruong/9508049

Now we have split the code blocks where the condition logic is defined in the condition block and the main logic is in the while body.

Do Loop Expressions

A do loop is similar to a while loop expression.

The difference is that the body is executed at least once before the condition is evaluated.

For expressions

There are two types of for expressions: a for comprehension and a for expression. In this session I will cover for expressions. Since this is one of the most feature in Scala I will go more in detail and show you more examples.

As stated in the specification:

'... A for loop for(enums) e executes expression e for each binding generated by the enumerators enums.'

In this example from the Scala Book you can iterate through a collection: https://gist.github.com/taitruong/9511571

The enumeration 'file <- filesHere' you can read as 'file in filesHere'. Basically it is an assignment of the collection 'filesHere' to the variable 'file'. Imagine the collection contains the files aFile, bFile, and cFile. In this example the for expression loops 3 times:

  • loop 1: assign aFile to file, print file
  • loop 2: assign bFile to file, print file
  • loop 3: assign cFile to file, print file

It is also possible to define several assignment variables if for example the enumeration is a map: https://gist.github.com/taitruong/9547505

Generators: Nested Enumerations

Further on in the specification it says:

'... An enumerator sequence always starts with a generator; this can be fol- lowed by further generators, value definitions, or guards.'

In the worksheet I have implemented a nested loop using two generators.

Guards: Filtering Generators

A generator followed by a guard filters a collection. A filter can be expressed like this:

if <boolean expression>

In this example it filters the first collection from 1 to 4 and accepts only even numbers. The result collection contains 2 and 4 being assigned to the val variable outer.

Pattern Matching

Another important and widely used feature is pattern matching. The Scala specification says the following about pattern matching:

'... A pattern matching expression

      e match { case p1 => b1 ... case pn => bn}

consists of a selector expression e and a number n > 0 of cases. Each case consists of a (possibly guarded) pattern pi and a block bi. Each pi might be complemented by a guard if e where e is a boolean expression. The scope of the pattern variables in pi comprises the pattern’s guard and the corresponding block bi.'

Constant Pattern

A simple example is using a constant pattern: https://gist.github.com/taitruong/9545243

Here we are checking the selector expression 'language' against two pattern cases: first with the constant pattern 'German', second with the constant pattern 'English'. In our case language matches the second pattern and executes its code block by printing 'Hello'.

Pattern Types

In Scala you can define several kinds of patterns. A pattern...

'... is built from constants, constructors, variables and type tests. Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values). The same variable name may not be bound more than once in a pattern.'

There are several kinds of patterns. Below I show you some examples for variable, typed, and constructor patterns.

Variable Pattern

Let me adjust the previous example and change the selector's value to 'Esperanto': https://gist.github.com/taitruong/9545411

The problem here is that both patterns does not match. What can I do? It would be bogus to define all possible cases. One possibility is to assign the selector to a variable and do something with it. In this case it acts like a default case: https://gist.github.com/taitruong/9545450

A special case is the wildcard pattern '... which is treated as if it was a fresh variable on each occurrence'. This allows you to ignore a pattern definition and match as a default case: https://gist.github.com/taitruong/9545627

The solution in the worksheet looks like this.

Typed Pattern

You can also match against a type. Taking the case class example from the last session we can check the sub classes Var, Number, and VarNumber: https://gist.github.com/taitruong/9547207

Constructor Pattern The above example can also be solved by constructor patterns: https://gist.github.com/taitruong/9547590

Resources

Built-in Control Structures