第三章作者重在阐述一种编程观念, 即 “data does indeed strcture programs”
这一章貌似没什么干货,只好把作者的几个例子贴出来,反复看看了。
1 A survey program
Total | US Citi | Perm Visa | Temp Visa | Male | Female | |
African American | 1289 | 1239 | 17 | 2 | 684 | 593 |
Mexican American | 675 | 577 | 80 | 11 | 448 | 219 |
Native American | 198 | 182 | 5 | 3 | 132 | 64 |
Spanish American | 411 | 223 | 152 | 20 | 224 | 179 |
Asian American | 519 | 312 | 152 | 41 | 247 | 270 |
Caucasian | 16272 | 15663 | 355 | 33 | 9367 | 6836 |
Other | 225 | 123 | 78 | 19 | 129 | 92 |
Totals | 19589 | 18319 | 839 | 129 | 11231 | 8253 |
1) the numbers should be stored as an array
ethnicgroup = entry[0] campus = entry[1] if entry[2] == refused declined[ethnicgroup, 2]++ else j = 1 + entry[2] count[campus, ethnicgroup, j]++ if entry[3] == refused declined[ethnicgroup, 3]++ else j = 4 + entry[3] count[campus, ethnicgroup, j]++
for i = [2, 8] if entry[i] == refused declined[ethnicgroup, i]++ else j = offset[i] + entry[i] count[campus, ethnicgroup, j]++
2) should the array be laid out to its output structure or its input structure?
The left one result in a little more work when the data was read and a little less work when it was written.
2 Form-letter programming
Welcome back, Jane! We hope that you and all the members of the Frank family are constantly reminding your neighbors there on Maple Street to shop with us. As usual, we will ship your order to Ms. Jane Q. Frank 60 Maple Street Your Town, Iowa 12345 ... ...
behind the scenes a computer looked up your user name in a database record and retrieved fields like
Frank | Jane | Q. | Ms.| 60 | Maple Street | Your Town | Iowa | 12345
seperate form letter generator from form letter schema
Welcome back, $1! We hope that you and all the members of the $0 family are constantly reminding your neighbors there on $5 to shop with us. As usual, we will ship your order to $3 $1 $2. $0 $4 $5 $6, $7 $8 ... ...
read fields from database loop from start to end of schema c = next character in schema if c != '$' printchar c else c = next character in schema case c of '$' : printchar '$' '0' - '9' : printstring field[c] default : error("bad schema")
3 Four principles
1) rework repeated code into arrays
a long stretch of similar code is often best expressed by the simplest of data structures, the array
2) encapsulate complex structures
define a sophisticated data structure in abstract terms, and express those operations as a class
3) use advanced tools when possible
Hypertext, name-value pairs, spreadsheets, databases, languages are powerful tools
4) let the data structure the program
before writing code, thoroughly understand the input, the output and the intermediate data structures