12.3.3.1 planar mappings in sequence expressions
Suppose we have a list of tuples of cities, each containing the name of the city and the country in which it resides, and we have a list of the cities that the user has chosen. Therefore, we can represent the sample data in this way:
Let cities = [("New York", "USA"); ("London", "UK");
("Cambridge", "UK"); ("Cambridge", "USA")]
Let entered = ["London"; " Cambridge "]
Now, suppose we want to find the country of the selected city. We can traverse the selected city in the cities list to find the country. You may have seen the problem with this approach: there is a city called Cambridge, both in the UK and in the United States, so you need to be able to return multiple records for a city. As you can see in Listing 12.10, we use two nested for loops in a sequence expression.
Listing 12.10 Using a sequence expression to join a collection (F # Interactive)
> seq {for name in entered do [1]
for (n, c) in cities do [2]
if (n = name) then | [3]
Yield sprintf "%s (%s)" N c};; |
Val it:seq<string> = | Back to Cambridge.
Seq ["London (UK)"; " Cambridge (UK) "; "Cambridge (USA)"] | Two countries
The outer for loop iterates through the name [1] in entered, and the nested loop traverses the cities list [2]. Thus, within the nested loop body, we can compare the name of each input city to the name of each known city. If the name is the same, the code nested within two loops [3] uses the yield statement to generate a project, and if the name is different, no element is produced.
In the case of database terminology, this operation can be explained by a join (jion). Enter a list of names and a list containing city information, using the city name as the key to join. It is easy to write this code using a sequence expression, which is the preferred way to join programming in F #.
As we mentioned, any sequence expression can be written as an operation using a planar map, so we can look at how to explicitly use Seq.collect to rewrite the previous example. You will not actually do this, but it will be invaluable when we look at defining our own, sequential expressions, similar to the alternative workflow.
12.3.3.1 planar mappings in sequence expressions