Introduction to Computer Science Lecture 6: Programming Languages

Similar documents
Chapter 6: Programming Languages

Second-generation: Assembly language. Figure 6.1 Generations of programming languages. Assembly Language Characteristics.

Chapter 5: Algorithms

Linguaggi di Programmazione

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.

Programmiersprachen (Programming Languages)

St. MARTIN S ENGINEERING COLLEGE Dhulapally, Secunderabad

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Introduction to Programming Using Java (98-388)

Informatica 3 Syntax and Semantics

Object Oriented Paradigm

Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful?

Final-Term Papers Solved MCQS with Reference

Programming Languages, Summary CSC419; Odelia Schwartz

Logic Programming II & Revision

Com S 541. Programming Languages I

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

Pierce Ch. 3, 8, 11, 15. Type Systems

LECTURE 18. Control Flow

Semester Review CSC 301

Data Types. (with Examples In Haskell) COMP 524: Programming Languages Srinivas Krishnan March 22, 2011

Types. What is a type?

Type Inference Systems. Type Judgments. Deriving a Type Judgment. Deriving a Judgment. Hypothetical Type Judgments CS412/CS413

Intermediate Code Generation Part II

A Tour of Language Implementation

1 Terminology. 2 Environments and Static Scoping. P. N. Hilfinger. Fall Static Analysis: Scope and Types

CS558 Programming Languages

CSC 533: Organization of Programming Languages. Spring 2005

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

COMPILER DESIGN LECTURE NOTES

General Concepts. Abstraction Computational Paradigms Implementation Application Domains Influence on Success Influences on Design

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Implementing Subprograms

Program Abstractions, Language Paradigms. CS152. Chris Pollett. Aug. 27, 2008.

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

2. The object-oriented paradigm!

Programming Paradigms

Principles of Programming Languages. Lecture Outline

8/27/17. CS-3304 Introduction. What will you learn? Semester Outline. Websites INTRODUCTION TO PROGRAMMING LANGUAGES

Motivation was to facilitate development of systems software, especially OS development.

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

HANDLING NONLOCAL REFERENCES

Lecture 12: Data Types (and Some Leftover ML)

EMBEDDED SYSTEMS PROGRAMMING Language Basics

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

C++ (Non for C Programmer) (BT307) 40 Hours

COS 140: Foundations of Computer Science

CS133 C Programming. Instructor: Jialiang Lu Office: Information Center 703

More C++ : Vectors, Classes, Inheritance, Templates

Programming Language Concepts 1982, 1987, Outline. Period

22c:111 Programming Language Concepts. Fall Types I

Part (04) Introduction to Programming

Lecture 6 Introduction to Objects and Classes

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

CSE 307: Principles of Programming Languages

CSc 372. Comparative Programming Languages. 2 : Functional Programming. Department of Computer Science University of Arizona

Continuations provide a novel way to suspend and reexecute

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Motivation was to facilitate development of systems software, especially OS development.

Seminar in Programming Languages

NOTE: Answer ANY FOUR of the following 6 sections:

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

SKILL AREA 304: Review Programming Language Concept. Computer Programming (YPG)

Programming Languages Third Edition. Chapter 7 Basic Semantics

Topic I. Introduction and motivation References: Chapter 1 of Concepts in programming languages by J. C. Mitchell. CUP, 2003.

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Lecture 09. Ada to Software Engineering. Mr. Mubashir Ali Lecturer (Dept. of Computer Science)

Concepts of Programming Languages

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CSCI-GA Scripting Languages

Introduction to Engineering Using Robotics Experiments. Dr. Yinong Chen

The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

Computer Components. Software{ User Programs. Operating System. Hardware

Example: Haskell algebraic data types (1)

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

CSE 307: Principles of Programming Languages

Chapter 1. Preliminaries

6.096 Introduction to C++ January (IAP) 2009

VALLIAMMAI ENGINEERING COLLEGE

Babaria Institute of Technology Computer Science and Engineering Department Practical List of Object Oriented Programming with C

BM214E Object Oriented Programming Lecture 4

Programming in C++ 4. The lexical basis of C++

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

CS558 Programming Languages

Low-Level Languages. Computer Programs and Programming Languages

Types and Type Inference

2. The object-oriented paradigm

1st Semester MTCE 601A COMPUTER SYSTEM SOFTWARE

Introduction to Compiler Construction

Inheritance, and Polymorphism.

Concepts in Programming Languages

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

Transcription:

Introduction to Computer Science Lecture 6: Programming Languages Tian-Li Yu Taiwan Evolutionary Intelligence Laboratory (TEIL) Department of Electrical Engineering National Taiwan University tianliyu@cc.ee.ntu.edu.tw Slides made by Tian-Li Yu, Jie-Wei Wu, and Chu-Yu Hsu Tian-Li Yu Programming Languages 1 / 45

Programming Languages and Paradigms PL Generations 1st 2nd 3rd 4th Machine Instructions Assembly (Mnemonic system of MIs) Fortran Cobol Basic C/C++ Java SQL SAS Tian-Li Yu Programming Languages 2 / 45

Programming Languages and Paradigms Assembler: Translating MIs to Assembly 1 st Machine instructions 2 nd Assembly 156C LD R5, Price 166D LD R6, ShippingCharge 5056 ADDI R0, R5, R6 306E ST R0, TotalCost C000 HTL Mnemonic names for op-codes Identifiers: Descriptive names for memory locations, chosen by the programmer Tian-Li Yu Programming Languages 3 / 45

Programming Languages and Paradigms 3 rd Generation Languages (3GL) Characteristics of assembly - Machine dependent - One-to-one mapping - Assembler High-level primitives Machines independent (virtually) One primitive to many MI mapping Compiler & interpreter Tian-Li Yu Programming Languages 4 / 45

Languages and Issues Programming Languages and Paradigms Natural vs. formal languages - Formal language formal grammar Portability - Theoretically: different compilers - Reality: Minor modifications Tian-Li Yu Programming Languages 5 / 45

Programming Paradigms Programming Languages and Paradigms LISP ML Schema Functional C++ C# Smalltalk Visual Basic Java Object-oriented Machine Languages FORTRAN BASIC COBOL ALGOL APL C Pascal Ada Imperative GPSS Prolog Declarative 1950 1960 1970 1980 1990 2000 Tian-Li Yu Programming Languages 6 / 45

Programming Languages and Paradigms Imperative vs. Declarative Imperative paradigm - Procedural - Approaching a problem by finding an algorithm to solve the problem. Declarative paradigm - Implemented a general problem solver - Approaching a problem by finding a formal description of the problem. - Will talk more about this later. Tian-Li Yu Programming Languages 7 / 45

Functional Paradigm Programming Languages and Paradigms Inputs: Old_balance Credits Debits Find_sum Find_sum Find_diff Output: New_balance Tian-Li Yu Programming Languages 8 / 45

Programming Languages and Paradigms Functional vs. Imperative (Find diff (Find sum Old balance Credits) (Find sum Debits)) Temp balance Old balance + Credit Total debits sum of all Debits Balance Temp balance Total debits (Find Quotiant (Find sum Numbers) (Find count Numbers)) Sum sum of all Numbers Count # of Numbers Quotiant Sum / Count Tian-Li Yu Programming Languages 9 / 45

Programming Languages and Paradigms Object-Oriented Paradigm OOP (object-oriented programming) Abstraction Information hiding - Encapsulation - Polymorphism Inheritance References: - http://www.codeproject.com/kb/architecture/oop_concepts_and_manymore.aspx - http://en.wikipedia.org/wiki/object-oriented_programming Tian-Li Yu Programming Languages 10 / 45

Imperative Paradigm More about Imperative Paradigm Variables and data types Data structure Constants and literals Assignment and operators Control Comments Tian-Li Yu Programming Languages 11 / 45

Variables and Data Types Integer Real (floating-point) Character Boolean Imperative Paradigm FORTRAN INTEGER a, b REAL c, d BYTE e, f LOGICAL g, h Pascal a, b: integer; c, d: real; e, f: char; g, h: boolean; C/C++ (Java) int a, b; float c, d; char e, f; bool g, h; Tian-Li Yu Programming Languages 12 / 45

Imperative Paradigm Data Structure Homogeneous array Heterogeneous array FORTRAN INTEGER a(6,3) Pascal a: array[0..5,0..2] of integer; C/C++ int a[5][2]; C/C++ struct{ char Name[25]; int Age; float SkillRating; } Employee; Tian-Li Yu Programming Languages 13 / 45

Imperative Paradigm Constant and Literals a b + 645; - 645 is a literal const int a=645; final int a=645; A constant cannot be a l-value. - a=b+c; Tian-Li Yu Programming Languages 14 / 45

Assignment and Operators Imperative Paradigm APL a <- b + c; Ada, Pascal a := b + c; C/C++ (Java) a = b + c; Operator precedence Operator overloading Tian-Li Yu Programming Languages 15 / 45

Imperative Paradigm Control Old-fashion: goto goto 40 20 print "passed." goto 70 40 if (grade < 60) goto 60 goto 20 60 print "failed." 70 stop Not recommended in modern programming Modern programming if (grade < 60) then print "failed." else print "passed." Tian-Li Yu Programming Languages 16 / 45

Imperative Paradigm Control Structures Condition true S1 B? Condition false S2 if (B) S1 else S2; Condition false B? Condition true S1 while (B) S1; S1 N = C1 What is the value of N? N = C2 S2 S3 N = C3 switch (N) { case C1: S1;break; case C2: S2;break; case C3: S3;break; }; Tian-Li Yu Programming Languages 17 / 45

Control Structures (contd.) Imperative Paradigm Assign Count the value 1 False Count < 4? True Body Assign Count the value Count + 1 for (int Count = 1; Count < 4; Count++) body; Tian-Li Yu Programming Languages 18 / 45

Imperative Paradigm Comments C/C++, Java a = b + c; // This is an end-of-line comment /* This is a block comment */ a = b + c; /** This is a documentation comment */ a = b + c; Tian-Li Yu Programming Languages 19 / 45

Imperative Paradigm Calling Procedures Calling program unit Control is transferred to procedure Procedure Calling program unit requests procedure. Procedure is excuted. Calling program unit continues Control is returned to calling enviroment when procedure is completed. Tian-Li Yu Programming Languages 20 / 45

Imperative Paradigm Terminology Starting the head with the term void is the way that a C programmer specifies that the program unit is a procedure rather than a function. We will learn about functions shortly. The former parameter list. Note that C, as with many programming languages, requires that the data type of each parameter be specified. void ProjectPopulation (float GrowthRate){ int Year; Population[0] = 100.0; for (Year = 0; Year =< 10; Year++) Population[Year+1] = Population[Year] + (Population[Year]*GrowthRate); } This declares a local variable named Year. These statements describe how the populations are to be computed and stored in the global array named Population. Tian-Li Yu Programming Languages 21 / 45

Imperative Paradigm Terminology (contd.) Procedure s header Local vs. global variables Formal vs. actual parameters Passing parameters - Call by value (passed by value) - Call by reference (passed by reference) - Call by address: variant of call-by-reference. Tian-Li Yu Programming Languages 22 / 45

Imperative Paradigm Call by Value a. When the procedure is called, a copy of data is given to the procedure Calling environment Procedure s environment 5 5 procedure Demo(Formal ) Formal Formal + 1; b. and the procedure manipulates its copy. Calling environment Procedure s environment 5 6 Demo(Actual); c. Thus, when the procedure has terminated, the calling environment has not changed. Calling environment 5 Tian-Li Yu Programming Languages 23 / 45

Imperative Paradigm Call by Reference a. When the procedure is called, the formal parameter becomes a reference to the actual parameter. Calling environment Procedure s environment Actual Formal 5 procedure Demo(Formal ) Formal Formal + 1; Demo(Actual); C/C++ void Demo(int& Formal){ Formal = Formal + 1; } b. Thus, changes directed by the procedure are made to the actual parameter Calling environment Procedure s environment Actual 6 Formal c. and are, therefore, preserved after the procedure has terminated. Calling environment Actual 6 Tian-Li Yu Programming Languages 24 / 45

Functions vs. Procedures Imperative Paradigm A program unit similar to a procedure unit except that a value is transferred back to the calling program unit as the value of the function. The function header begins with the type of the data that will be returned. float CylinderVolumn (float Radius, float Height){ float Volume; Volume = 3.14 * Radius * Radius * Height; return Volume; } Terminate the function and return the value of the variable Volume This declares a local variable named Volume. Compute the volume of the cylinder Tian-Li Yu Programming Languages 25 / 45

Imperative Paradigm The Translation Process Lexical analyzer: identifying tokens. Parser: identifying syntax & semantics. Source program Lexical analyzer Parser Code generator Object program Tian-Li Yu Programming Languages 26 / 45

Syntax Diagrams for Algebra Imperative Paradigm Expression Term + - Expression Term Factor + x Term Factor x y z Tian-Li Yu Programming Languages 27 / 45

Imperative Paradigm Grammar for Algebra Expression Term Term + Expression Term - Expression Term Factor Factor * Term Factor / Term Factor x y z Starting: Expression Nonterminals: Expression, Term, Factor Terminals: x, y, z Tian-Li Yu Programming Languages 28 / 45

Imperative Paradigm Parse Tree x + y z Expression Term + Expression Factor Term x Factor x Term y Factor z Tian-Li Yu Programming Languages 29 / 45

Imperative Paradigm Ambiguity if B1 then if B2 then S1 else S2 Statement Statement if Boolean expression then Statement else Statement if Boolean expression then Statement B1 B1 if Boolean expression then Statement if Boolean then else expression Statement Statement B2 S1 B2 S1 S2 Tian-Li Yu Programming Languages 30 / 45

Imperative Paradigm Code Generation Coercion: implicit conversion between data types Strongly typed: no coercion, data types have to agree with each other. Code optimization - x = y + z; - w = x + z; - w = y + (z << 1); Tian-Li Yu Programming Languages 31 / 45

Object-Oriented Paradigm OOP Object - Active program unit containing both data and procedures Class - A template from which objects are constructed - An object is an instance of the class. Instance variables & methods (member functions) Constructors - Special method used to initialize a new object when it is first constructed. Destructors vs. garbage collection Tian-Li Yu Programming Languages 32 / 45

Object-Oriented Paradigm An Example of Class Instance variable Constructor assigns a value to Remaining Power when an object is created. class LaserClass { int RemainingPower; LaserClass (InitialPower) { RemainingPower = InitialPower; } void turnright ( ) {... } void turnleft ( ) {... } methods void fire ( ) {... } } Tian-Li Yu Programming Languages 33 / 45

Object-Oriented Paradigm Encapsulation Encapsulation - A way of restricting access to the internal components of an object - Bundling of data with the methods operating on that data. Examples: private vs. public, getter & setter Tian-Li Yu Programming Languages 34 / 45

Object-Oriented Paradigm Polymorphism Polymorphism - Allows method calls to be interpreted by the object that receives the call. - Allows different data types to be handled using a uniform interface. Circle(); Rectangle(); Circle circle; Rectangle rect; circle.draw(); rect.draw(); Tian-Li Yu Programming Languages 35 / 45

Object-Oriented Paradigm Inheritance Inheritance - Allows new classes to be defined in terms of previously defined classes. Class Base; Class Circle : Base; Class Rectangle : Base; Base *base; Circle circle; Rectangle rect; base = & circle; base -> draw(); base = & rect; base -> draw(); Tian-Li Yu Programming Languages 36 / 45

Object-Oriented Paradigm Concurrency Mutual Exclusion: A method for ensuring that data can be accessed by only one process at a time. Monitor: A data item augmented with the ability to control access to itself Calling program unit procedure is activated. Procedure Calling program unit requests procedure. Both units excute simultaneiously. Tian-Li Yu Programming Languages 37 / 45

Declarative Programming Declarative Programming Resolution - Combining two or more statements to produce a new statement (that is a logical consequence of the originals). - (P OR Q) AND (R OR Q) resolves to (P OR R) - Resolvent: A new statement deduced by resolution - Clause form: A statement whose elementary components are connected by OR Unification - Assigning a value to a variable so that two clauses would be the same. - Unify(Father(Mark,John), Father(x,John)) results in x is Mark. Tian-Li Yu Programming Languages 38 / 45

Declarative Programming Proof by Resolution (Refutation) We know that (P OR Q) AND (R OR Q) AND ( R) is true (KB, knowledge base). We want to prove that P is true. Prove by showing that KB AND p is unsatisfiable (empty clause). P OR Q R OR Q R P P OR R P empty clause Tian-Li Yu Programming Languages 39 / 45

Declarative Programming Prolog Variables: first letter capitalized (exactly contrary to common logics). Constants: first letter uncapitalized. Facts: - Consists of a single predicate - predicatename(arguments). parent(bill, mary). Rules: - conclusion :- premise. :- means if - faster(x,z) :- faster(x,y), faster(y,z). Operators: is, ==, =, <, >, +, -, *, /, =>, =< Tian-Li Yu Programming Languages 40 / 45

Gnu Prolog Declarative Programming Prolog Gnu prolog http://www.gprolog.org/ Interactive mode - Under the prompt?-, type [user]. - When finished, type Ctrl-D Comments - /* */ or % Chinese incompatible. You may consult *.pl (a pure text file) Tian-Li Yu Programming Languages 41 / 45

Prolog Examples Declarative Programming Prolog bill mary female(mary). female(sue). male(bill). male(john). parent(mary,john). parent(bill,john). parent(mary,sue). parent(bill,sue). john sue mother(x,y): female(x),parent(x,y). father(x,y): male(x),parent(x,y). son(x,y): male(x),parent(y,x). daughter(x,y): female(x),parent(y,x). sibling(x,y): X\=Y,parent(Z,X),parent(Z,Y). Tian-Li Yu Programming Languages 42 / 45

Declarative Programming Prolog Prolog Examples Factorial again. If we want Prolog to compute factorials, we need to tell it what factorials are. factorial(0,1). factorial(n,f) : N>0, N1 is N 1, factorial(n1,f1), F is N * F1.? factorial(5,w). W=120? Tian-Li Yu Programming Languages 43 / 45

Fibonacci Revisited Declarative Programming Prolog f(0,1). f(1,1). f(n,f) : N>0, N1 is N 1, N2 is N 2, f(n1,f1), f(n2,f2), F is F1 + F2. f(n,f) : c(n,,,f). c(0,0,0,1). c(1,0,1,1). c(2,1,1,2). c(n,p1,p2,p3): N>2, N1 is N 1, c(n1, P0, P1, P2), P2 is P0+P1, P3 is P1+P2. How about f(40,w)? Tian-Li Yu Programming Languages 44 / 45

Declarative Programming Prolog Ordered Clauses factorial(0,1). factorial(n,f) : N>0, factorial(n1,f1), N1 is N 1, F is N * F1.? factorial(3,w). Try these commands: listing. trace. notrace. This wouldn t work, why? Tian-Li Yu Programming Languages 45 / 45