《Composing Programs》学习笔记(1)Chapter 1: Building Abstractions with Functions(关键词:软件工程/抽象/函数)

来源:互联网 发布:莽荒纪披风进阶数据 编辑:程序博客网 时间:2024/05/24 02:37

Chapter 1: Building Abstractions(抽象) with Functions

1.1 Getting Started

Computer science is a tremendously(非常地) broad academic(学术的) discipline(学科). The areas of globally distributed(分布式的) systems, artificial(人造的) intelligence(智力), robotics(机器人学), graphics(图形), security, scientific computing, computer architecture(建筑学), and dozens of emerging(浮现) sub-fields all expand(扩张) with new techniques and discoveries every year. The rapid progress of computer science has left few aspects(方面) of human life unaffected. Commerce(贸易), communication, science, art, leisure(空闲的), and politics have all been reinvented(重新使用) as computational(计算的) domains.

The high productivity(生产力) of computer science is only possible because the discipline(学科) is built upon an elegant(高雅的) and powerful set of fundamental(基本的) ideas. All computing begins with representing information, specifying(指定) logic(逻辑) to process it, and designing abstractions that manage the complexity(复杂) of that logic(设计抽象,用以管理那种逻辑的复杂度). Mastering(精通) these fundamentals(原理;原则;基础) will require us to understand precisely(精确地) how computers interpret(说明) computer programs and carry out computational processes.

These fundamental ideas(基本理念) have long been taught using the classic(经典的) textbook Structure(结构) and Interpretation of Computer Programs (SICP) by Harold Abelson and Gerald Jay Sussman with Julie Sussman. This text borrows heavily from that textbook, which the original authors have kindly licensed for adaptation(适应) and reuse under a Creative Commons license. These notes are published under the Creative(创造性的) Commons attribution(归因) non-commericial share-alike license version 3.

1.1.1 Programming in Python

    A language isn't something you learn so much as something you join.                                                             —Arika Okrent

In order to define(定义) computational processes, we need a programming language; preferably(较好) one that many humans and a great variety of computers can all understand. In this text, we will work primarily(首要地,主要地) with the Python language.

Python(巨蟒) is a widely used programming language that has recruited(招聘) enthusiasts(狂热者) from many professions: web programmers, game engineers, scientists, academics, and even designers of new programming languages. When you learn Python, you join a million-person-strong community of developers. Developer communities are tremendously() important institutions(机构): members help each other solve problems, share their projects and experiences, and collectively(共同地) develop software and tools. Dedicated(致力) members often achieve celebrity(名人) and widespread esteem(尊重) for their contributions.

The Python language itself is the product of a large volunteer community that prides itself on the diversity of its contributors(贡献者). The language was conceived(怀孕) and first implemented(实施) by Guido van Rossum in the late 1980’s. The first chapter of his Python 3 Tutorial explains why Python is so popular, among the many languages available today.

Python(巨蟒) excels as an instructional(教学的) language because, throughout its history, Python’s developers have emphasized(强调) the human interpretability(可解释性) of Python code, reinforced(加强) by the Zen of Python guiding principles(原理) of beauty, simplicity(朴素), and readability(可读性). Python is particularly appropriate(适当的) for this text because its broad set of features(特色) support a variety of different programming styles, which we will explore. While there is no single way to program in Python, there are a set of conventions(大会) shared across the developer community that facilitate(促进) reading, understanding, and extending(延伸) existing programs. Python’s combination(结合) of great flexibility(灵活性) and accessibility(易接近) allows students to explore many programming paradigms(范例), and then apply their newly acquired(获得) knowledge to thousands of ongoing projects.

These notes maintain(维持) the spirit of SICP by introducing the features of Python in step with techniques for abstraction(抽象) and a rigorous(严格的) model of computation(估计). In addition, these notes provide a practical introduction to Python programming, including some advanced language features and illustrative(说明的) examples. Increasing your facility(设施) with Python should come naturally as you progress through the text.

The best way to get started programming in Python is to interact(互相影响) with the interpreter(解释者) directly. This section describes how to install(安装) Python 3, initiate(开始) an interactive(交互式的) session(会议) with the interpreter, and start programming.

1.1.2 Installing Python 3

As with all great software, Python has many versions. This text will use the most recent stable(稳定的) version of Python 3. Many computers have older versions of Python installed already, such as Python 2.7, but those will not match the descriptions in this text. You should be able to use any computer, but expect to install Python 3. (Don’t worry, Python is free.)

You can download Python 3 from the Python downloads page by clicking on the version that begins with 3 (not 2). Follow the instructions of the installer(安装程序) to complete installation(安装).

For further guidance, try these video tutorials(个别指导) on Windows installation and Mac installation of Python 3, created by Julia Oh.

1.1.3 Interactive Se(交互式的)ssions(会议)

In an interactive Python session, you type some Python code after the prompt, >>>. The Python interpreter reads and executes(实行) what you type, carrying out your various commands.

To start an interactive session, run the Python 3 application. Type python3 at a terminal prompt(敏捷的) (Mac/Unix/Linux) or open the Python 3 application in Windows.

If you see the Python prompt, >>>, then you have successfully started an interactive(交互式的) session(会议). These notes depict(描述) example interactions(相互作用) using the prompt, followed by some input(投入).

>>> 2 + 24

Interactive controls. Each session keeps a history of what you have typed. To access that history, press -P (previous) and -N (next). -D exits a session, which discards(抛弃) this history. Up and down arrows also cycle through history on some systems.

1.1.4 First Example

And, as imagination(想象力) bodies forth(向前)The forms of things to unknown, and the poet's penTurns them to shapes, and gives to airy(空气的) nothingA local habitation(居住) and a name.                                            —William Shakespeare, A Midsummer-Night's Dream

To give Python a proper introduction, we will begin with an example that uses several language features(特色). In the next section, we will start from scratch(擦伤) and build up the language piece by piece. Think of this section as a sneak(暗中进行的) preview of features to come.

Python(巨蟒) has built-in(嵌入的) support for a wide range of common programming activities, such as manipulating(操纵) text, displaying graphics(图形), and communicating over the Internet. The line of Python code

>>> from urllib.request import urlopen

is an import statement(声明) that loads functionality(功能) for accessing data on the Internet. In particular, it makes available a function called urlopen, which can access the content at a uniform resource locator(定位器) (URL), a location of something on the Internet.

Statements & Expressions. Python(巨蟒) code consists of expressions and statements. Broadly, computer programs consist of instructions to either

1.Compute some value2.Carry out some action

Statements typically(代表性地) describe actions. When the Python interpreter(说明) executes(实行) a statement, it carries out the corresponding action. On the other hand, expressions typically describe computations(估计). When Python evaluates(评价) an expression, it computes the value of that expression. This chapter introduces several types of statements and expressions.

The assignment statement

>>> shakespeare = urlopen('http://composingprograms.com/shakespeare.txt')

associates the name shakespeare with the value of the expression that follows =. That expression applies the urlopen function to a URL that contains the complete text of William Shakespeare’s 37 plays, all in a single text document.

Functions. Functions encapsulate(压缩) logic(逻辑) that manipulates(操纵) data. urlopen is a function. A web address is a piece of data, and the text of Shakespeare’s plays is another. The process by which the former leads to the latter may be complex(复杂的), but we can apply that process using only a simple expression because that complexity(复杂) is tucked(卷起) away within a function. Functions are the primary topic of this chapter.

Another assignment(分配) statement(声明)

>>> words = set(shakespeare.read().decode().split())

associates the name words to the set of all unique(独特的) words that appear in Shakespeare’s plays, all 33,721 of them. The chain of commands to read, decode, and split, each operate on an intermediate(起媒介作用) computational(计算的) entity(实体): we read the data from the opened URL, then decode the data into text, and finally split the text into words. All of those words are placed in a set.

Objects. A set is a type of object, one that supports set operations like computing intersections(交叉) and membership(资格). An object seamlessly(无缝的) bundles(束) together data and the logic(逻辑) that manipulates(操纵) that data, in a way that manages the complexity(复杂) of both. Objects are the primary topic of Chapter 2. Finally, the expression

>>> {w for w in words if len(w) == 6 and w[::-1] in words}{'redder', 'drawer', 'reward', 'diaper', 'repaid'}

is a compound(复合的) expression that evaluates(评价) to the set of all Shakespearian words that are simultaneously(同时地) a word spelled in reverse(相反). The cryptic(神秘的) notation(符号) w[::-1] enumerates(列举) each letter in a word, but the -1 dictates(命令) to step backwards. When you enter an expression in an interactive(交互式的) session(会议), Python prints its value on the following line.

Interpreters. Evaluating compound expressions requires a precise(精确的) procedure(程序) that interprets(说明) code in a predictable(可预言的) way. A program that implements(工具) such a procedure, evaluating compound expressions, is called an interpreter. The design and implementation(实现) of interpreters is the primary topic of Chapter 3.

When compared with other computer programs, interpreters for programming languages are unique(独特的) in their generality(概论). Python(巨蟒) was not designed with Shakespeare in mind. However, its great flexibility(灵活性) allowed us to process a large amount(数量) of text with only a few statements(声明) and expressions.

In the end, we will find that all of these core concepts(观念) are closely related: functions are objects, objects are functions, and interpreters are instances(实例) of both. However, developing a clear understanding of each of these concepts and their role in organizing code is critical(鉴定的) to mastering the art of programming.

1.1.5 Errors

Python is waiting for your command. You are encouraged to experiment with the language, even though you may not yet know its full vocabulary and structure(结构). However, be prepared for errors. While computers are tremendously(非常地) fast and flexible(灵活的), they are also extremely rigid(严格的). The nature of computers is described in Stanford’s introductory(引导的) course as

The fundamental(基本的) equation(方程式) of computers is:computer = powerful + stupidComputers are very powerful, looking at volumes(量) of data very quickly. Computers can perform billions of operations per second, where each operation is pretty simple.Computers are also shockingly stupid and fragile. The operations that they can do are extremely rigid(严格的), simple, and mechanical(机械的). The computer lacks anything like real insight(洞察力) ... it's nothing like the HAL 9000 from the movies. If nothing else, you should not be intimidated(恐吓) by the computer as if it's some sort of brain. It's very mechanical underneath(在…的下面) it all.Programming is about a person using their real insight to build something useful, constructed out of these teeny(极小的), simple little operations that the computer can do.                —Francisco Cai and Nick Parlante, Stanford CS101

The rigidity(硬度) of computers will immediately become apparent(显然的) as you experiment with the Python interpreter(说明): even the smallest spelling and formatting(格式化) changes will cause unexpected(意外的) output(输出) and errors.

Learning to interpret errors and diagnose(诊断) the cause of unexpected errors is called debugging. Some guiding principles(原理) of debugging(调试以排除故障) are:

1.Test incrementally: Every well-written program is composed(构成) of small, modular(模块化的) components(成分) that can be tested individually(个别地). Try out everything you write as soon as possible to identify(确定) problems early and gain confidence in your components.
2.Isolate errors: An error in the output of a statement(声明) can typically(代表性地) be attributed(归属) to a particular modular component. When trying to diagnose a problem, trace(追踪) the error to the smallest fragment(碎片) of code you can before trying to correct it.
3.Check your assumptions: Interpreters do carry out your instructions to the letter — no more and no less. Their output is unexpected when the behavior o(行为)f some code does not match what the programmer believes (or assumes) (承担)that behavior to be. Know your assumptions, (假定)then focus your debugging effort on verifying t(核实)hat your assumptions actually hold.
4.Consult others: You are not alone! If you don’t understand an error message, ask a friend, instructor(指导书), or search engine. If you have isolated(孤立的) an error, but can’t figure out how to correct it, ask someone else to take a look. A lot of valuable programming knowledge is shared in the process of group problem solving.

Incremental(增加的) testing, modular design, precise(精确的) assumptions, and teamwork are themes that persist(存留) throughout this text. Hopefully, they will also persist throughout your computer science career(事业).

Continue: 1.2 Elements(元素) of Programming

参考文献:
1.http://composingprograms.com/

阅读全文
0 0
原创粉丝点击