11.1.2.1 using variable data structures
In Listing 11.4, you can see two functions, and the processed collection holds the name of the previous example. This time, we use C # to keep the place names in the standard list<t> type, which is mutable.
Listing 11.4 Dealing with place names stored in list<t> (C #)
List<string> loadplaces () {[1]
Returnnew list<string> {"Seattle", "Prague",
"NewYork", "Grantchester", "Cambridge"};
}
void Printlongest (list<string> names) {[2]
Varlongest = Names[0]; <--First Outer place name
for (inti = 1; i < names. Count; i++)
if (Names[i]. Length > Longest. Length) longest = names[i]; <--remember the longest name of the current
Console.WriteLine (longest);
}
void Printmultiword (list<string> names) {[3]
Names. RemoveAll (s=>!s.contains ("")); <--Delete Only one word of the name
Console.WriteLine ("Withspace: {0}", names. Count);
}
The first function loads the sample data [1], like the previous loadplaces function, except that there is no population value; Next, two processing functions are implemented, the first function [2] finds the longest name, and the second function [3] determines the number of place names that contain multiple words by removing the names that do not contain spaces. Although the method uses the syntax of the lambda function, it is certainly not functional: Because the RemoveAll method modifies the Names collection. If we are going to use these functions in a later program, we can write the code like this:
Printmultiword (Loadplaces ()); Prints ' 1 '
Printlongest (Loadplaces ()); Prints ' Grantchester '
Although the correct result is obtained, however, two calls to the Loadplaces function, which seems to be unnecessary. If a function loads data from a database, it is better to retrieve the data only one time for performance reasons. You can do simple refactoring, call the function once, and save the place name in a local variable:
var places = Loadplaces ();
Printmultiword (places); Prints ' 1 '
Printlongest (places); Prints ' New York '
After a simple change, we failed to get the right results! If you carefully read the trace source code, you may have found the problem:list<t> is a mutable data structure, the function Printmultiword when calling RemoveAll, accidentally modified it, when we call printlongest after the code, The collection places contains only one item, which is "NewYork". Now, let's see if we're using immutable data structures, why there's no such error.
11.1.2.1 using variable data structures