1. Trang chủ
  2. » Công Nghệ Thông Tin

Nguyên lý các ngôn ngữ lập trình Lập trình chỉ thị

43 380 2
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Nguyên lý các ngôn ngữ lập trình Lập trình chỉ thị
Người hướng dẫn Dr. Huỳnh Quyết Thắng, Assoc. Prof
Trường học Hanoi University of Science and Technology
Chuyên ngành Computer Science/Programming
Thể loại lecture notes
Năm xuất bản Unknown
Thành phố Hà Nội
Định dạng
Số trang 43
Dung lượng 613,35 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Content of Lesson 1. Imperative Programming Model 2. Memory Management 3. Some Typical Programming Techniques 4. Some exercises Command in an imperative language were simple abstraction of the instruction in standard con Neumann machines These included assignment statement, conditional statement, branch statement, loop statement

Trang 1

IT6020 Nguyên lý các ngôn ngữ

lập trình

Lecturer: Dr Huỳnh Quyết Thắng, Assoc Prof at Dept of Software Engineering,

SoICT, HUST Email: thanghq@soict.hut.edu.vn

Chương 2 – Lập trình chỉ thị

Trang 3

1 Imperative Programming model

Von Neumann machine has a memory, which contains both programming instruction (the program store) and data values (data store)

Imperative languages have variable declaration, expression and command

 Declaration assign names to memory allocation

and associate types with stores values

 Expression are interpreted in term of the currentvalue in the data store

 Commands are normally executed in the ordr they

appear in the program store, although conditional

Trang 4

1 Imperative Programming model

Command in an imperative language were simple abstraction of the instruction in standard con Neumann machines

These included assignment statement, conditional statement, branch statement, loop statement

Trang 5

1.1 Feature of imperative programming languages

Data type for integer, real, characters, string,booleans and their operator

Control structures: statement sequencing,conditionals, branching statements, for and whileloop, case (switch) statement

Assignment statement

Array and element assignment

Record structures and element assignment

Input and output commands

Pointer

Procedure and function

Trang 6

1.2 Naming and Variables

The model uses a single-assignment store, which is a

set of variables that are initially unbound and that can

be bound to one value

Trang 7

1.2 Naming and Variables

Declarative variables: Variables in the single-assignment

store are called declarative variables We use this term

whenever there is a possible confusion with other kinds of

variables Later we will also call these variables dataflow

variables because of their role in dataflow execution.

Once bound, a declarative variable stays bound throughout the computation and is indistinguishable from its value What this means is that it can be used in calculations as if it were the value.

Doing the operation x + y is the same as doing 11 + 22, if the store is {x = 11, y = 22}.

Trang 8

1.2 Naming and Variables

Value store: A store where all variables are bound

to values is called a value store A value is a

314 or [1 2 3]

Trang 9

1.2 Naming and Variables

Variable identifiers: So far, we have looked at a

store that contains variables and values, i.e., store

entities, with which calculations can be done It

would be nice if we could refer to a store entity fromoutside the store This is the role of variable

identifiers A variable identifier is a textual name

that refers to a store entity from outside the store.The mapping from variable identifiers to store

entities is called an environment.

Trang 10

1.2 Naming and Variables

Variable-variable binding: Variables can be bound to

variables For example, consider two unbound variables x1

and y1 referred to by the identifiers X and Y.

 x1=X

 y1=Y

Dataflow variables: In the declarative model, creating a

variable and binding it are done separately What happens if

we try to use the variable before it is bound? We call this a

variable use error.

Trang 11

1.3 Elementary Types, Value and Expression

Trang 12

1.3 Elementary Types, Value and Expression

Expression in real language:

 Scope resolution

 Member Selection

 Unary negation, complement increment,

address-of, de-reference, allocate, de-allocate

 Multiply, divide, Modulo

 Add, Subtract

 Left Shift, Right Shift

 Less than , Less or Equal, Greater than, Greater orEqual

Trang 13

1.3 Elementary Types, Value and Expression

Expression in real language (continue):

 Equal, not Equal

Conversion anf Type casting:

 A conversion is just the translation of a data value from one type to an equivalent value in another type

Trang 14

1.4 Syntax and Semantics of statements in real

DoStatement-> do Statement while (Expression)

Switch (Case) statements

SwitchStatement->switch (Expression) {cases}

Cases->Case Cases | Default

Case->CaseHead Cases | CaseHead Statement

CaseHead-> case Literal;

Default->default : statement

Break, continue

Trang 15

1.4 Scope, Visibility and Lifetime

The Scope of a variable is that collection ofstatements which can access that variable

Static scoping: variable reference can be resolved byinspections of the source text of the program withoutregard to its execution history The static scope of aglobal variable includes all statement in the programLocal and global variable:

Dynamic and static allocation:

Trang 16

Each block of memory continuously cycles through

three states: active, inactive, and free Memory

management is the task of making sure that memory

circulates correctly along this cycle

A running program that needs a block of memory

will allocate it from a pool of free memory blocks.

Trang 17

2 Memory Management

Trang 18

2 Memory Management

Values in programming language can be assigned toany of three different categories of memory: staticmemory, the runtime-stack and the heap

Static memory is allocated to values whose storagerequirement are known before run time and remainconstant throughout the life of the running program.The run-time stack is the center of control fordispatching active methods (procedures andfunctions), their local variables, their parameterslinkages and they gain relinquish control to thecaller

Trang 21

Whenever a method is called a new set of “local”declaration is allocated space on the run-time stack.This space is part of a block called stack frame

The stack frame contains spaces for the calledmethods argument value, local variables, a staticlink to the static ares and dynamic link to the stackframe for the method that called this method

2.1 Method, Locals, Parameters and the Runtime Stack

Trang 22

Example Program with Methods and Parameters

Trang 23

Run-Time Stack with Stack Frames for Method Invocations

Trang 24

Passing an Argument

by Reference Example

Trang 26

int [] A= new int [10]

“dope vector” contains information that enableseffective addressing and type checking of references

to individual entries

Trang 27

Dynamic Memory Allocation for t

he One-Dimensional Array A

Trang 28

Memory Allocation for Two-Dimensional Array C

Trang 30

2.4 Memory Leak and Garbage Collection

Dangling reference (widow) This happens when a

block is reclaimed even though it is still reachable.The system will eventually reuse this block Thismeans that data structures will be corrupted inunpredictable ways, causing the program to crash.This error is especially pernicious since the effect(the crash) is usually very far away from the cause(the incorrect reclaiming) This makes danglingreferences hard to debug

Trang 31

2.4 Memory Leak and Garbage Collection

Memory leak This happens when an unreachable

block is considered as still reachable, and so is notreclaimed The effect is that active memory sizekeeps growing indefinitely until eventually thesystem’s memory resources are exhausted Memoryleaks are less dangerous than dangling referencesbecause programs can continue running for sometime before the error forces them to stop Long-lived programs, such as operating systems andservers, must not have any memory leaks

Trang 32

Creating Widows and Orphans: A Simple Example

p = new node();

q = new node();

q=p;

delete p;

Trang 33

2.4 Memory Leak and Garbage Collection

Many high-level languages, such as Erlang, Haskell,Java, Lisp, Prolog, Smalltalk, and so forth, do

automatic reclaiming That is, reclaiming is done by

the system independently of the running program.This completely eliminates dangling references andgreatly reduces memory leaks This relieves theprogrammer of most of the difficulties of manualmemory management Automatic reclaiming is

called garbage collection Garbage collection is a

well-known technique that has been used for a long

Trang 34

2.4 Memory Leak and Garbage Collection

It was used in the 1960’s for early Lisp systems.Until the 1990’s, mainstream languages did not use

it because it was incorrectly judged as being tooinefficient It has finally become acceptable inmainstream programming because of the popularity

of the Java language

Three major strategies have served as a foundation for modern garbage collection algorithms: reference counting, mark-sweep and copy collection

Trang 35

2.4 Memory Leak and Garbage Collection

Reference counting: The principle behind reference counting is to store a counter in every object indicating the number of references to the object The counters of the affected objects must be updated every time the mutator modifies the object graph When creating a new reference to

an object the counter must be incremented, and when removing a reference the counter must be decremented.

Trang 36

2.4 Memory Leak and Garbage Collection

Mark-Sweep: called into action only when theheap is full Mark-sweep algorithms make use of

two phases; the marking phase and the sweeping

phase The purpose of the marking phase is to

locate and mark all objects that are reachable fromthe mutator The second phase, the weeping phase,traverses the heap examining each object andreclaims the memory occupied by unmarkedobjects The sweeping phase may includecompaction of the heap, in which case the algorithm

is sometimes called mark-compact.

Trang 37

2.4 Memory Leak and Garbage Collection

Copy Collection: Copy collection represents a kind

of time-space compromise when it is compared withmark-sweep Heap is divided in two identicalblocks, called from_space and the to_space Here,

no extra field is required in each node for areference count or mark bit

Instead, all the active nodes are initially resident inthe from_space, the to_space is unused and free_listpoints to the next available block in the from_spacethat can be allocated

Trang 39

3 Some typical Programming Techniques

Iterative computation: We will now look at how

to program in the imperative model We start bylooking at a very simple kind of program, the

iterative computation An iterative computation is a

loop whose stack size is bounded by a constant,independent of the number of iterations This kind

of computation is a basic programming tool Thereare many ways to write iterative programs It is notalways obvious when a program is iterative.Therefore, we start by giving a general schema thatshows how to construct many interesting iterativecomputations in the imperative model

Trang 40

3.1 Iterative Programming Techniques

A general schema: An important class of

iterative computations starts with an initial

state S0 and transforms the state in successive steps until reaching a final state Sfinal:

S0 -> S1-> · · · -> Sfinal

An iterative computation of this class can be written as a general schema:

fun Iterate (Si)

if IsDone (Si) then Si

else Si+1= Transform (Si)

Trang 41

3.2 Recursive Programming Techniques

A recursive method is a method that contains a

statement (or statements) that makes a call to itselfThe three necessary components in a recursive

method are:

 A test to stop or continue the recursion

 An end case that terminates the recursion

 A recursive call(s) that continues the recursion

To ensure that the recursion will stop eventually, we must pass arguments different from the incoming

parameters into the recursive call

Trang 42

3.2 Recursive Programming Techniques

When we use Recursion:

• A recursive solution is natural and easy to

Comparision Recursive and Iterative Programming

(Time running, memory using, )

Trang 43

1. Tìm bổ sung tài liệu và mô tả 3 thuật toán

Reference counting, Mark-sweep, Copy

Collection

2. Sử dụng một ngôn ngữ bất kỳ để viết chương trình

theo phương pháp lặp và phương pháp đệ quy giải một trong các bài toán điển hình: dãy fibonachi

(fibonachi series), Tháp Hà Nội (Hanoi Tower),

Xử lý thao tác trên cây (tree structure processing)

3. Tổng hợp các kỹ thuật chuyển đổi các chương

trình đệ quy sang chương trình sử dụng vòng lặp

Ngày đăng: 28/07/2014, 00:33

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm

w