Chapter 4 Control flow

Version 1.1 for TouchDevelop v2.8 Control Flow Chapter 4 Control flow We now start our journey into real programming with TouchDevelop. TouchDevelop...
Author: Alicia Warren
0 downloads 0 Views 861KB Size
Version 1.1 for TouchDevelop v2.8

Control Flow

Chapter 4 Control flow We now start our journey into real programming with TouchDevelop. TouchDevelop is not just a language, but also an environment that lets you access everything on your phone – songs, pictures, contacts and so on. We shall be showing examples of how this is done in the next few chapters. A list of songs is called a collection, and in this chapter we shall talk about the variety of collections that are available. To work through a collection, we need loop constructs. By the end of this chapter, you will have been introduced to the different kinds of loops The three kinds of looping statements are explained using some simple examples. The bodies of these loops contain code which tests the values held by loop index variables, so this chapter also provides examples of if statements. One kind of loop, the for each loop, is used with instances of collection types, so that topic should be covered first.

4.1.

Overview of Collections

4.2.

The for each Loop

4.3.

The while Loop

4.4.

The for Loop

Overview of Collections The TouchDevelop API provides access to several kinds of collection. The collection types currently supported by the API are listed in Tables (a) The TouchDevelop Mutable Collection Types to 4.2. As in other high level languages, a collection is exactly as it sounds – a collection of values. An array provides one way to implement a collection in a program; a linked-list is another common implementation for a collection. In TouchDevelop, the implementation of collections is hidden from the user. A script can step through the values in a collection or index the collection to access, say, the 15 item. th

Some kinds of collections are mutable. These are the ones listed in Table 4.1(a). It means that a script can create a new collection and add or remove elements from it. Other kinds of collection are immutable. These are the ones listed in Table 4.1(b).Since there are many collection types in the table, they have been grouped into three categories. ‘Immutable’ means that a collection (such as a list of songs on the phone or a list of home network

– 41 –

Control Flow

Version 1.1 for TouchDevelop v2.8

devices) can be obtained, but the elements of the collection can only be accessed. There are no methods for adding or removing elements from an immutable collection.

Table 4.1: (a) The TouchDevelop Mutable Collection Types Type

Description

Link Collection

A list of links; each link is a reference to a video, image, email, or phone num-

Location Collection

A list of locations; each location is a coordinate pair

Message Collection

A list of messages

Place Collection

A collection of places

Sprite Set

A collection of sprites

String Collection

A collection of strings

ber

There are a few methods which are common to all collections. These are described in Table 4.2. In the left-hand column of this table, each entry shows the complete signature for the method. For example, the at method takes a single argument of type Number and it returns a single result of the element type (denoted by the word ELEMTYPE). This is similar to how methods are documented on the TouchDevelop website. Note the table omits two methods which are also available for all collection types. That is because these two methods can be used with all datatypes. They are is invalid

and

post to wall.

The is invalid method tests whether a usable value has been assigned to the variable being tested (or has been returned from a method that was invoked) and yields a true or false value. The post to wall method displays some representation of the value on the screen. The nature of the representation depends on the datatype.

– 42 –

Version 1.1 for TouchDevelop v2.8

Control Flow

Table 4.1: (b) The TouchDevelop Immutable Collection Types Type

Description Social Details Collections

Appointment Collection

A collection of appointments

Contact Collection

A collection of contacts Media Collections

Picture Albums

A collection of picture albums

Pictures

A collection of pictures

Playlists

A collection of song playlists

Songs

A collection of songs Home Network Collections

Device Collection

A collection of devices on the home network

Media Link Collection

A list of links to media on the home network

Media Player Collection

A list of devices for playing media on the home network

Media Server Collection

A list of media servers on the home network

Printer Collection

A collection of printers on the home network

– 43 –

Control Flow

Version 1.1 for TouchDevelop v2.8

Table 4.2: Standard Methods for Mutable and Immutable Collection Types Method

Description retrieves an element of the collection at a particular position (the first

at(pos: Number): ELEMTYPE

count: Number

element is at position 0). The type of the result is the same type as the elements in the collection. returns the number of elements in the collection selects and returns a random element of the collection (this method

random: ELEMTYPE

is provided for many but not all collection types)

There are a few more methods which are common to all mutable collection types. These are listed in Table 4.3. Other methods for collections are specific to each collection type and will only be described as we come to them.

Table 4.3: Additional Standard Methods for all Mutable Collections Method

Description The method is accessed via the collections service. There is one create method for all mutable collection types except sprite set;

create XX: COLLECTIONTYPE

for example create place collection is one such method, and the result has type Place Collection. Adds a new element e to the end of the collection of

add(e: ELEMTYPE): Nothing

clear: Nothing

ELEMTYPE values removes all elements from the collection

Figure Creating and Using a Mutable Collection shows some sample code which creates a mutable collection, adds some elements to it, displays the size, removes an element, and then gives the size again.

– 44 –

Version 1.1 for TouchDevelop v2.8

Control Flow

Figure 4.1: Creating and Using a Mutable Collection action main( ) var names := collections→create string collection names→add("Joan") names→add("Jane") names→add("Jill") names→count→post to wall names→remove("Jane") names→count→post to wall

The for each Loop It is frequently the case that we want our script to examine or use each element of one of these collections. The

for each loop is used exactly for that purpose.

Example: Iterating over all pictures held on the Phone Figure First for-each Example (pictures and dates) shows a script which checks each picture held on the phone and displays the picture and the date it was taken.

Figure 4.2: First for-each Example (pictures and dates) action main( ) for each pic in media→pictures where true do pic→resize(64,64) pic→post to wall pic→date→post to wall

The local variable pic is assigned a reference to a different picture in the collection on each iteration of the loop. The where clause component of the for each loop can be used to select a subset of values in the collection. In this example, we want to display information about every element in the collection and so the test provided after the keyword where is the Boolean constant true. Note that pic is a read-only variable, assignments to pic are not allowed.

Example: Find all pictures on the Phone less than one day old This example is very similar to the previous one, but we are selecting only those pictures which are less than 24 hours old to display. We have two obvious ways to test whether a picture should be displayed or not. We can

– 45 –

Control Flow

Version 1.1 for TouchDevelop v2.8

use an if statement in the scripting language or we can take advantage of the where clause attached to the for

each loop. Both versions are shown in Figure Second FOR EACH Example (selecting recent pictures).

Figure 4.3: Second FOR EACH Example (selecting recent pictures) action main()

action main()

version 1 of the program

version 2 of the program

for each pic in media→pictures

for each pic in media→pictures

where true

where (time→now

do

→subtract(pic→date))

if (time→now→subtract(pic→date))

≤ (24 * 60 * 60)

≤ (24 * 60 * 60) then

do

pic→resize(64,64)

pic→resize(64,64)

pic→post to wall

pic→post to wall

pic→date→post to wall

pic→date→post to wall

else do nothing Some explanation of how the script tests the age of each picture is probably required. The expression time→now returns the current time of day; it is returned as a DateTime value. Similarly the expression pic→date returns the time at which the picture was taken as a DateTime value. The DateTime datatype provides a method named subtract which computes the difference between two DateTime values as a number of seconds. We simply have to compare this difference with the number of seconds in a day.

Example: Display the durations of all songs held on the Phone Figure Third FOR EACH Example (durations of songs) shows the code for a script which displays some simple information about each song found on the phone – namely the name of the song and its duration. Note the similarity with Figure First for-each Example (pictures and dates): iterating over the elements in a collection tends to look much the same no matter what kind of elements are held in that collection.

Figure 4.4: Third FOR EACH Example (durations of songs) action main( ) for each song in media→songs where true do song→name→post to wall song→duration→post to wall

– 46 –

Version 1.1 for TouchDevelop v2.8

Control Flow

Example: Finding and Playing the shortest song held on the Phone As another illustration of the use of if statements, Figure Fourth FOR EACH Example (shortest song) shows a script which searches through all the songs to find the one with the shortest duration and then starts playing that song. The variable shortest holds the duration of the shortest song found so far. Using a value provided in the math resource, we initialize its value to plus infinity. The variable named which holds the shortest song found so far. Since the scripting language requires an initial value for that variable, we assign it a special INVALID value. The body of the loop tests whether the current song being inspected is shorter than the shortest found so far. If the test succeeds, we update the shortest and which variables.

Figure 4.5: Fourth FOR EACH Example (shortest song) action main( ) var shortest := math→∞₊ var which := invalid→song for each song in media→songs where true do if song→duration ≤ shortest then which := song shortest := song→duration else do nothing the loop has terminated

which→play This script can of course be modified so that the where clause is used instead of an if statement.

– 47 –

Control Flow

Version 1.1 for TouchDevelop v2.8

The while Loop The while loop in the TouchDevelop scripting language looks syntactically similar to while loops in many programming languages and also behaves similarly.

Example: Using a while loop to implement a countdown timer To illustrate a while loop, we show a countdown timer. It starts at 10.0 seconds and displays the time remaining as a descending sequence in tenths of a second: 10.0 9.9 9.8 ... 0.2 0.1 0.0. At this point, the Windows phone takes a picture. The script is shown in Figure A while Loop Example (countdown timer)..

Figure 4.6: A while Loop Example (countdown timer) action main( ) var timer := 10.0 while timer > 0 do wall→clear timer→post to wall timer := timer - 0.1 time→sleep(0.1) the loop has terminated

var pic := senses→camera→preview pic→post to wall

In this script, we clear the wall before displaying the new time duration. If we did not do that, each of the time durations would be written as a separate line, inserted one above the other. Better still, we should display the remaining time using very large digits. However that requires the use of a textbox or some graphics programming. We will display large digits in the new version of the program which is coming next.

– 48 –

Version 1.1 for TouchDevelop v2.8

Control Flow

The for Loop A for loop uses an index variable which takes on successive integer values starting from zero and continuing up to some limit. The index variable is read-only.

Example: Using a for loop to implement a countdown timer The script shown in Figure A FOR Loop Example (countdown timer) is functionally equivalent to the previous script (Figure A while Loop Example (countdown timer)) except that it uses a for loop to iterate 100 times and it draws the remaining time in large characters at random positions and in random colors on the screen.

Figure 4.7: A FOR Loop Example (countdown timer) action main() for 0 ≤ i < 100 do wall→clear var pic := media→create picture(480, 800) pic→draw text(math→rand(350), math→rand(575), i, 150, 0, colors→rand) pic→post to wall time→sleep(0.1) the loop has terminated

senses→camera→preview→post to wall

– 49 –

Control Flow

Version 1.1 for TouchDevelop v2.8

– 50 –