PPL Complete Notes Jntuh
PPL Complete Notes Jntuh
ON
PRINCIPLES OF PROGRAMMING
LANGUAGES
Course Objective:
To study various programming paradigms.
To provide conceptual understanding of High level language design and
implementation.
To introduce the power of scripting languages
Learning Outcome:
Select appropriate programming language for problem solving
Design new programming language.
Gain Knowledge and comparison of the features of programming languages
UNIT I
Unit 1: Introduction: Software Development Process, Language and Software
Development Environments, Language and Software Design Models, Language and
Computer Architecture, Programming Language Qualities, A brief Historical Perspective.
Syntax and Semantics: Language Definition, Language Processing, Variables, Routines,
Aliasing and Overloading, Run-time Structure.
Unit 2: Structuring the data: Built-in types and primitive types, Data aggregates and type
constructors, User-defined types and abstract data types, Type Systems, The type Structure
of representative languages, Implementation Models
Unit 3: Structuring the Computation: Expressions and Statements, Conditional Execution
and Iteration, Routines, Exceptions, Pattern Matching, Nondeterminism and Backtracking,
Event-driven computations, Concurrent Computations
Structuring the Program: Software Design Methods, Concepts in Support of Modularity,
Language Features for Programming in the Large, Generic Units
Unit 4: Object-Oriented Languages: Concepts of Object-oriented Programming,
Inheritances and the type system, Object-oriented features in programming languages
Unit 5: Functional Programming Languages: Characteristics of imperative languages,
Mathematical and programming functions, Principles of Functional Programming,
Representative Functional Languages, Functional Programming in C++
Logic and Rule-based Languages: ―What versus ―how: Specification versus
implementation, Principles of Logic Programming, PROLOG, Functional Programming
versus Logic Programming, Rule-based Languages.
TEXT BOOKS:
1. Programming Language Concepts‖, Carlo Ghezzi, Mehdi Jazayeri, WILEY
Publications. Third Edition, 2014
REFERENCE BOOKS
1. Concepts of Programming Languages, Tenth Edition, Robert W. Sebesta, Pearson
Education.
2. Programming Languages Principles and Paradigms, Second Edition, Allen B. Tucker,
Robert E. Noonan, McGraw Hill Education.
3. Introduction to Programming Languages, Aravind Kumar Bansal, CRC Press
UNIT - 1
INTRODUCTION
Software Development Process
What is a Software Development Process?
A software development process or life cycle is a structure imposed on the development of a software
product. There are several models for such processes, each describing approaches to a variety of tasks
or activities that take place during the process.
Processes
The Capability Maturity Model (CMM) is one of the leading models. Independent assessments can be
used to grade organizations on how well they create software according to how they define and execute
their processes.
There are dozens of others, with other popular ones being ISO 9000, ISO 15504, and Six Sigma.
Process Activities/Steps
Software Engineering processes are composed of many activities, notably the following:
Requirements Analysis
o Extracting the requirements of a desired software product is the first task in creating it. While customers probably believe they know what the software is to do, it may
require skill and experience in software engineering to recognize incomplete, ambiguous or contradictory requirements.
Specification
o Specification is the task of precisely describing the software to be written, in a mathematically rigorous way. In practice, most successful specifications are written to
understand and fine-tune applications that were already well-developed, although safety-critical software systems are often carefully specified prior to application
development. Specifications are most important for external interfaces that must remain stable.
Software architecture
o The architecture of a software system refers to an abstract representation of that system. Architecture is concerned with making sure the software system will meet the
requirements of the product, as well as ensuring that future requirements can be addressed.
Implementation
o Reducing a design to code may be the most obvious part of the software engineering job, but it is not necessarily the largest portion.
Testing
o Testing of parts of software, especially where code by two different engineers must work together, falls to the software engi neer.
Documentation
o An important task is documenting the internal design of software for the purpose of future maintenance and enhancement.
o A large percentage of software projects fail because the developers fail to realize that it doesn't matter how much time and planning a development team puts into creating
software if nobody in an organization ends up using it. People are occasionally resistant to change and avoid venturing into an unfamiliar area, so as a part o f the
deployment phase, its very important to have training classes for the most enthusiastic software users (build excitement and confidence), shifting the training towards the
neutral users intermixed with the avid supporters, and finally incorporate the rest of the organization into adopting the new software. Users will have lots of questions and
software problems which leads to the next phase of software.
Maintenance
o Maintaining and enhancing software to cope with newly discovered problems or new requirements can take far more time than the initial development of the software. Not
only may it be necessary to add code that does not fit the original design but just determining how software works at some point after it is completed may require
significant effort by a software engineer. About 60% of all software engineering work is maintenance, but this statistic can be misleading. A small part of that is fixing
bugs. Most maintenance is extending systems to do new things, which in many ways can be considered new work.
It is believed that the depth at which we think is influenced by the expressive power of the
language in which we communicate our thoughts. It is difficult for people to
conceptualize structures they can‘t describe, verbally or in writing.
Language in which they develop S/W places limits on the kinds of control structures,
data structures, and abstractions they can use.
Awareness of a wider variety of P/L features can reduce such limitations in S/W
development.
Can language constructs be simulated in other languages that do not support those
constructs directly?
Many programmers, when given a choice of languages for a new project, continue to use
the language with which they are most familiar, even if it is poorly suited to new
projects.
If these programmers were familiar with other languages available, they would be in a
better position to make informed language choices.
Programmers who understand the concept of OO programming will have easier time
learning Java.
The more languages you gain knowledge of, the better understanding of
programming languages concepts you understand.
In some cases, a language became widely used, at least in part, b/c those in
positions to choose languages were not sufficiently familiar with P/L
concepts.
Many believe that ALGOL 60 was a better language than Fortran; however,
Fortran was most widely used. It is attributed to the fact that the
programmers and managers didn‘t understand the conceptual design of
ALGOL 60.
Do you think IBM has something to do with it?
Programming Domains
Scientific applications
Business applications
– The arrival of PCs started new ways for businesses to use computers.
– Symbolic computation is more suitably done with linked lists than arrays.
Systems programming
– The O/S and all of the programming supports tools are collectively known as its
system software.
Scripting languages
– PHP is a scripting language used on Web server systems. Its code is embedded in
HTML documents. The code is interpreted on the server before the document is
sent to a requesting browser.
Readability
Language constructs were designed more from the point of view computer than the users.
– Too many features make the language difficult to learn. Programmers tend to
learn a subset of the language and ignore its other features. ―ALGOL 60
– Ex ―Java:
++count
– Although the last two statements have slightly different meaning from each other
and from the others, all four have the same meaning when used as stand-alone
expressions.
– Operator overloading where a single operator symbol has more than one meaning.
– Although this is a useful feature, it can lead to reduced readability if users are
allowed to create their own overloading and do not do it sensibly.
Orthogonality:
Control Statements
– It became widely recognized that indiscriminate use of goto statements severely reduced
program readability.
sum += incr;
incr++;
loop1:
incr++;
go to loop1: out:
– Basic and Fortran in the early 70s lacked the control statements that allow strong
restrictions on the use of gotos, so writing highly readable programs in those languages
was difficult.
– The control statement design of a language is now a less important factor in readability
than it was in the past.
– The presence of adequate facilities for defining data types and data structures in a
language is another significant aid to reliability.
Syntax Considerations
– The syntax of the elements of a language has a significant effect on readability.
– The following are examples of syntactic design choices that affect readability:
Identifier forms: Restricting identifiers to very short lengths detracts from readability. ANSI
BASIC (1978) an identifier could consist only of a single letter of a single letter followed by a
single digit.
Special Words: Program appearance and thus program readability are strongly influenced by the
forms of a language‘s special words. Ex: while, class, for. C uses braces for pairing control
structures. It is difficult to determine which group is being ended. Fortran 95 allows programmers
to use special names as legal variable names.
Form and Meaning: Designing statements so that their appearance at least partially indicates
their purpose is an obvious aid to readability.
Writability
It is a measure of how easily a language can be used to create programs for a chosen problem
domain.
Most of the language characteristics that affect readability also affect writability.
– A smaller number of primitive constructs and a consistent set of rules for combining
them is much better than simply having a large number of primitives.
– Abstraction means the ability to define and then use complicated structures or
operations in ways that allow many of the details to be ignored.
Expressivity
– It means that a language has relatively convenient, rather than cumbersome, ways of
specifying computations.
Reliability
A program is said to be reliable if it performs to its specifications under all conditions.
Type checking: is simply testing for type errors in a given program, either by the compiler or
during program execution.
– The earlier errors are detected, the less expensive it is to make the required repairs.
Java requires type checking of nearly all variables and expressions at compile
time.
Exception handling: the ability to intercept run-time errors, take corrective measures,
and then continue is a great aid to reliability.
Aliasing: it is having two or more distinct referencing methods, or names, for the same memory
cell.
– Compiling programs
– Executing programs
We use imperative languages, at least in part, because we use von Neumann machines
• Iteration is efficient
1950s and early 1960s: Simple applications; worry about machine efficiency
– Structured programming
– data abstraction
Language Categories
Imperative
– C, Pascal
– LISP, Scheme
Logic
– Rule-based
– Prolog
Object-oriented
– C++, Java
Programming Environments
UNIX
Borland JBuilder
Syntax - the form or structure of the expressions, statements, and program units Semantics - the
meaning of the expressions, statements, and program units Who must use language definitions?
Implementers
A lexeme is the lowest level syntactic unit of a language (e.g., *, sum, begin) A token is a category
of lexemes (e.g., identifier)
Language recognizers:
Because most useful languages are, for all practical purposes, infinite, this might seem like
a lengthy and ineffective process. Recognition devices, however, are not used to enumerate all of
the sentences of a language—they have a different purpose.
The syntax analysis part of a compiler is a recognizer for the language the compiler
translates. In this role, the recognizer need not test all possible strings of characters from some set
to determine whether each is in the language.
Language Generators
A language generator is a device that can be used to generate the sentences of a language.
The syntax-checking portion of a compiler (a language recognizer) is not as useful a language
description for a programmer because it can be used only in trial-and-error mode. For example, to
determine the correct syntax of a particular statement using a compiler, the programmer can only
submit a speculated version and note whether the compiler accepts it. On the other hand, it is often
possible to determine whether the syntax of a particular statement is correct by comparing it with
the structure of the generator.
Context-Free Grammars
A derivation is a repeated application of rules, starting with the start symbol and
ending with a sentence (all terminal symbols)
An example grammar:
An example grammar:
Syntax Graphs - put the terminals in circles or ellipses and put the nonterminals in rectangles;
connect with lines with arrowheads e.g., Pascal type declarations
Attribute Grammars (AGs) (Knuth, 1968) Cfgs cannot describe all of the syntax of
programming languages
- Additions to cfgs to carry some semantic info along through parse tree Primary value
of AGs:
Each rule has a set of functions that define certain attributes of the nonterminals in the
rule
Each rule has a (possibly empty) set of predicates to check for attribute consistency
Let X0 -> X1 ... Xn be a rule Functions of the form S(X0) = f(A(X1), ... A(Xn)) define synthesized
attributes Functions of the form I(Xj) = f(A(X0), ... , A(Xn)), for i <= j <= n, define inherited
attributes Initially, there are intrinsic attributes on the leaves
types of the two id's must be the same type of the expression must match it's expected
type
BNF:
Ambiguous grammar
A grammar is ambiguous if it generates a sentential form that has two or more distinct
parse trees An ambiguous expression grammar:
If we use the parse tree to indicate precedence levels of the operators, we cannot
have ambiguity An unambiguous expression grammar:
Optional parts are placed in brackets ([]) <proc_call> -> ident [ ( <expr_list>)]
Put alternative parts of RHSs in parentheses and separate them with vertical
bars term> -> <term> (+ | -) const
Put repetitions (0 or more) in braces ({}) <ident> -> letter {letter | digit}
BNF:
actual_type - synthesized for <var> and <expr> expected_type - inherited for <expr>
If all attributes were inherited, the tree could be decorated in top-down order.
If all attributes were synthesized, the tree could be decorated in bottom-up order.
In many cases, both kinds of attributes are used, and it is some combination of top-down and
bottom-up that must be used
<var>[1].actual_type =? <var>[2].actual_type 4.
<expr>.actual_type <var>[1].actual_type
<expr>.actual_type =? <expr>.expected_type
Dynamic Semantics
Operational Semantics
The detailed characteristics of the particular computer would make actions difficult to
understand
The process:
Build a translator (translates source code to the machine code of an idealized computer)
Axiomatic Semantics
Approach: Define axioms or inference rules for each statement type in the language (to
A weakest precondition is the least restrictive precondition that will guarantee the postcondition
An example: a := b + 1 {a > 1}
Program proof process: The postcondition for the whole program is the desired results. Work
back through the program to the first statement. If the precondition on the first statement is the
same as the program spec, the program is correct.
{I} B {I} (evaluation of the Boolean must not change the validity of I)
The loop invariant I is a weakened version of the loop postcondition, and it is also a
precondition.
I must be weak enough to be satisfied prior to the beginning of the loop, but when combined
with the loop exit condition, it must be strong enough to force the truth of the postcondition
It is a good tool for correctness proofs, and excellent framework for reasoning about
programs, but it is not as useful for language users and compiler writers
De-notational Semantics
Based on recursive function theory The most abstract semantics description method
Originally developed by Scott and Strachey
The process of building a de-notational spec for a language:
Define a function that maps instances of the language entities onto instances of the
corresponding mathematical objects
The meaning of language constructs are defined by only the values of the program's variables
The difference between denotational and operational semantics: In operational semantics, the
state changes are defined by coded algorithms; in denotational semantics, they are defined by
rigorous mathematical functions
The state of a program is the values of all its current variables s = {<i1, v1>, <i2,
v2>,…, <in, vn>}
Let VARMAP be a function that, when given a variable name and a state, returns the current
value of the variable
<dec_num> 0|1|2|3|4|5|6|7|8 |9
| <dec_num> (0 | 1 | 2 | 3 | 4 |
5|6|7|8 | 9)
<var> =>
else VARMAP(<var>, s)
<binary_expr> =>
The meaning of the loop is the value of the program variables after the statements in the loop
have been executed the prescribed number of times, assuming there have been no errors
– In essence, the loop has been converted from iteration to recursion, where the
recursive control is mathematically defined by other recursive state mapping
functions
– Recursion, when compared to iteration, is easier to describe with mathematical rigor
Data Types:
– Primitive
– not defined in terms of other data types
– Structured
– built out of other types
Integer Types:
Usually based on hardware
– Representing Integers:
– Can convert positive integers to base
– Ones complement
Twos Complement:
• To get the binary representation, take the complement and add 1
– For scientific use support at least two floating-point types (e.g., float and double;
sometimes more)
– The float type is the standard size, usually being stored in four bytes of memory.
– The double type is provided for situations where larger fractional parts and/or a larger
range of exponents is needed
– Floating-point values are represented as fractions and exponents, a form that is borrowed
from scientific notation
– Precision is the accuracy of the fractional part of a value, measured as the number of bits
– Range is a combination of the range of fractions and, more important, the range of
exponents.
– We can convert the decimal number to base 2 just as we did for integers
– fixed number of bits for the whole and fractional parts severely limits the range of
values we can represent
– Use a fixed number of bits for the exponent which is offset to allow for negative
exponents
– float
– double
– Some scripting languages only have one kind of number which is a floating point type
– Essential to COBOL
– Advantage: accuracy
C# decimal Type:
– 128-bit representation
-28 28
– Range: 1.0x10 to 7.9x10
– Precision: representation is exact to 28 or 29 decimal places (depending on size of
number)
– no roundoff error
– Boolean
– Range of values: two elements, one for ―true‖ and one for ―false‖
– A Boolean value could be represented by a single bit, but because a single bit of memory cannot
be accessed efficiently on many machines, they are often stored in the smallest efficiently
addressable cell of memory, typically a byte.
– ational (Scheme)
Character Strings :
– Character string constants are used to label output, and the input and output of all kinds
of data are often done in terms of strings.
– Operations:
– Catenation
– Substring reference
– Pattern matching
– C and C++
– Not primitive
– Primitive
– Java
– String class
String Implementation
– integer
– char
– boolean
– enumeration types
– ubrange types
Enumeration Types:
– All possible values, which are named constants, are provided in the definition
C example:
– Design issues
– duplication of names
– coercion rules
– toString and valueOf are overridden to make input and output easier
System.out.println (season);
Example:
– Ada’s design:
Type Days is (Mon, Tue, wed, Thu, Fri, sat, sun); Subtype Weekdays is Days range
Mon..Fri; Subtype Index is Integer range 1..100;
Evaluation
Subrange types enhance readability by making it clear to readers that variables of subtypes can
store only certain ranges of values. Reliability is increased with subrange types, because assigning a
value to a subrange variable that is outside the specified range is detected as an error, either by the
compiler (in the case of the assigned value being a literal value) or by the run-time system (in the case
of a variable or expression). It is odd that no contemporary language except Ada has subrange
types.
array_name(subscript_value_list) → element
– The binding of the subscript type to an array variable is usually static, but the subscript value
ranges are sometimes dynamically bound.
– There are five categories of arrays, based on the binding to subscript ranges, the binding to
storage, and from where the storage is allocated.
– A static array is one in which the subscript ranges are statically bound and storage allocation
is static (done before run time).
The disadvantage is that the storage for the array is fixed for the entire execution
time of the program.
– A fixed stack-dynamic array is one in which the subscript ranges are statically bound, but
the allocation is done at declaration elaboration time during execution.
– A stack-dynamic array is one in which both the subscript ranges and the storage allocation
are dynamically bound at elaboration time. Once the subscript ranges are bound and the
storage is allocated, however, they remain fixed during the lifetime of the variable.
The advantage of stack-dynamic arrays over static and fixed stack-dynamic arrays
is flexibility
– A fixed heap-dynamic array is similar to a fixed stack-dynamic array, in that the subscript
ranges and the storage binding are both fixed after storage is allocated
• A heap-dynamic array is one in which the binding of subscript ranges and storage allocation
is dynamic and can change any number of times during the array‘s lifetime.
– The disadvantage is that allocation and deallocation take longer and may happen
many times during execution of the program.
Array Initialization
Some languages provide the means to initialize arrays at the time their storage is allocated.
An array aggregate for a single-dimensioned array is a list of literals delimited by
parentheses and slashes. For example, we could have
Arrays of strings in C and C++ can also be initialized with string literals. In this case, the
array is one of pointers to characters.
For example,
In Java, similar syntax is used to define and initialize an array of references to String objects. For
example,
Ada provides two mechanisms for initializing arrays in the declaration statement: by listing
them in the order in which they are to be stored, or by directly assigning them to an index position
using the => operator, which in Ada is called an arrow.
A jagged array is one in which the lengths of the rows need not be the same.
For example, a jagged matrix may consist of three rows, one with 5 elements, one with 7
elements, and one with 12 elements. This also applies to the columns and higher dimensions. So,
if there is a third dimension (layers), each layer can have a different number of elements. Jagged
arrays are made possible when multi dimensioned arrays are actually arrays of arrays. For
example, a matrix would appear as an array of single-dimensioned arrays.
For example,
myArray[3][7]
Slices:
For example, if A is a matrix, then the first row of A is one possible slice, as are the last
row and the first column. It is important to realize that a slice is not a new data type. Rather ,it is a
mechanism for referencing part of an array as a unit.
Evaluation
If the element type is statically bound and the array is statically bound to storage, then the
value of the constant part can be computed before run time. However, the addition and
multiplication operations must be done at run time.
The generalization of this access function for an arbitrary lower bound is address (list[k]) =
address ( list [lower_bound]) + ( (k - lower_bound) * element_size)
CREC, Dept. of CSE Page 43
Associative Arrays
In Perl, associative arrays are called hashes, because in the implementation their elements
are stored and retrieved with hash functions. The namespace for Perl hashes is distinct: Every hash
variable name must begin with a percent sign (%). Each hash element consists of two parts: a key,
which is a string, and a value, which is a scalar (number, string, or reference). Hashes can be set to
literal values with the assignment statement, as in
%salaries = ("Gary" => 75000, "Perry" => 57000, "Mary" => 55750, "Cedric" => 47850);
Recall that scalar variable names begin with dollar signs ($). For example,
A new element is added using the same assignment statement form. An element can be
removed from the hash with the delete operator, as in
Delete $salaries{"Gary"};
Record Types
A record is an aggregate of data elements in which the individual elements are identified
by names and accessed through offsets from the beginning of the structure. There is frequently a
need in programs to model a collection of data in which the individual elements are not of the
same type or size. For example, information about a college student might include name, student
number, grade point average, and so forth. A data type for such a collection might use a character
string for the name, an integer for the student number, a floating point for the grade point average,
and so forth. Records are designed for this kind of need.
Definitions of Records
The fundamental difference between a record and an array is that record elements ,or
fields, are not referenced by indices. Instead, the fields are named with identifiers, and references
to the fields are made using these identifiers The COBOL form of a record declaration, which is
part of the data division of a COBOL program, is illustrated in the following example:
– EMPLOYEE-RECORD.
– EMPLOYEE-NAME.
The fields of records are stored in adjacent memory locations. But because the sizes of the
fields are not necessarily the same, the access method used for arrays is not used for records.
Instead, the offset address, relative to the beginning of the record, is associated with each field.
Field accesses are all handled using these offsets. The compile-time descriptor for a record has the
general form shown in Figure 6.7. Run-time descriptors for records are unnecessary
Name
Field 1
Type
Offset
…...
Name
field n Type
Offset
Address
Union Types
A union is a type whose variables may store different type values at different times during
program execution. As an example of the need for a union type, consider a table of constants for a
compiler, which is used to store the constants found in a program being compiled. One field of
each table entry is for the value of the constant. Suppose that for a particular language being
compiled, the types of constants were integer, floating point, and Boolean. In terms of table
management, it would be convenient if the same location, a table field, could store a value of any
of these three types. Then all constant values could be addressed in the same way. The type of
such a location is, in a sense, the union of the three value types it can store.
Design Issues
The problem of type checking union types, leads to one major design issue. The other
fundamental question is how to syntactically represent a union. In some designs, unions are
confined to be parts of record structures, but in others they are not. So, the primary design issues
that are particular to union types are the following:
Should type checking be required? Note that any such type checking must be dynamic.
Should unions be embedded in records?
Unions are implemented by simply using the same address for every possible variant.
Sufficient storage for the largest variant is allocated. The tag of a discriminated union is stored
with the variant in a record like structure. At compile time, the complete description of each
variant must be stored. This can be done by associating a case table with the tag entry in the
descriptor. The case table has an entry for each variant, which points to a descriptor for that
particular variant. To illustrate this arrangement, consider the following Ada example:
The descriptor for this type could have the form shown in Figure
Address
Sum
Float
– range of values that consists of memory addresses plus a special value, nil
– A pointer can be used to access a location in the area where storage is dynamically
created (usually called a heap)
– Dereferencing yields the value stored at the location represented by the pointer‘s value
j = *ptr
– void * can point to any type and can be type checked (cannot be de-referenced)
allocation
ptr = (int*)malloc(sizeof(int)
sizeof(
int))
Addison-Wesley
Pointer Problems:
Dereferencing a pointer
j = *ptr
Pointer Problems
Dangling pointers(dangerous)
Garbage
– An allocated heap-dynamic no
variable that is
Reference Types:
– C++ includes a special kind of pointer type called a reference type that is used primarily
for formal parameters
– Java extends C++‘s reference variables and allows them to replace pointers entirely
Evaluation of Pointers:
– Pointers are like goto's--they widen the range of cells that can be accessed by a variable
– Pointers or references are necessary for dynamic data structures--so we can't design a
language without them
– A machine consists of
Names:
– Maximum length?
Length of Names:
– Language examples:
– FORTRAN I: maximum 6
– COBOL: maximum 30
• Real VarName (Real is a data type followed with a name, therefore Real is a
keyword)
Variables:
– Name
– Address
– Value
– Type
– Lifetime
– Scope
Variable Attributes:
– Type - allowed range of values of variables and the set of defined operations Value -
the contents of the location with which the variable is associated (r-value
– Load time -- bind a FORTRAN 77 variable to a memory cell (or a C static variable)
– A binding is static if it first occurs before run time and remains unchanged throughout
program execution.
– A binding is dynamic if it first occurs during execution or can change during execution of
the program
Type Binding:
Type Checking
– Type checking is the activity of ensuring that the operands of an operator are of
compatible types
Compatible type :
It is one that is either legal for the operator, or is allowed under language rules to be implicitly
converted, by compiler- generated code, to a legal type
– If all type bindings are static, nearly all type checking can be static (done at compile
time)
– If type bindings are dynamic, type checking must be dynamic (done at run time)
– Advantage: allows the detection of misuse of variables that result in type errors
– C and C++
– Java is similar
Strong Typing:
– Advantage of strong typing: allows the detection of the misuses of variables that result in
type errors
– Language examples:
– C and C++ are not: parameter type checking can be avoided; unions are not type checked
Coercion rules strongly affect strong typing--they can weaken it considerably (C+ versus
Ada)
Although Java has just half the assignment coercions of C++, its strong typing is still far
less effective than that of Ada
Type Compatibility
Def: Name type compatibility means the two variables have compatible types if they are in
either the same declaration or in declarations that use the same type name
parameters (Pascal)
– Structure type compatibility means that two variables have compatible types if their types
have identical structures
Are two record types compatible if they are structurally the same but use different field
names?
Are two array types compatible if they are the same except that the subscripts are different?
– Are two enumeration types compatible if their components are spelled differently?
– With structural type compatibility, you cannot differentiate between types of the same
structure (e.g. different units of speed, both float)
Named Constants
Def: A named constant is a variable that is bound to a value only when it is bound to storage
The binding of values to named constants can be either static (called manifest constants)
or dynamic
Languages:
Variable Initialization
– Def: The binding of a variable to a value at the time it is bound to storage is called
initialization
• Java's strong typing is still far less effective than that of Ada
List = 17.3;
– But …
• The lifetime of a variable is the time during which it is bound to a particular memory cell
– Depending on the language, allocation can be either controlled by the programmer or done
automatically
Variable Scope:
– The nonlocal variables of a program unit are those that are visible but not declared there
– The scope rules of a language determine how references to names are associated with
variables
– Scope and lifetime are sometimes closely related, but are different concepts
Static Scope:
– To connect a name reference to a variable, you (or the compiler) must find the declaration
– Search process: search declarations, first locally, then in increasingly larger enclosing
scopes, until one is found for the given name Enclosing static scopes (to a specific scope)
are called its static ancestors; the nearest static ancestor is called a static parent
– Variables can be hidden from a unit by having a "closer" variable with the same name
– C++, Java and Ada allow access to some of these "hidden" variables
– In Ada: unit.name
– Suppose the spec is changed so that D must now access some data in B
– Solutions:
– Put D in B (but then C can no longer call it and D cannot access A's variables)
– Move the data from B that D needs to MAIN (but then all procedures can access
them)
Dynamic Scope:
Based on calling sequences of program units, not their textual layout (temporal versus
spatial)
References to variables are connected to declarations by searching back through the chain
of subprogram calls that forced execution to this point
– Reference to x is to MAIN's x
Dynamic scoping
– Reference to x is to SUB1's x
– Advantage: convenience
Referencing Environments:
– The referencing environment of a statement is the collection of all names that are visible in
the statement
– In a static-scoped language, it is the local variables plus all of the visible variables in all
of the enclosing scopes
– An operator can be unary, meaning it has a single operand, binary, meaning it has two
operands, or ternary, meaning it has three operands.
– In most programming languages, binary operators are infix, which means they appear
between their operands.
– One exception is Perl, which has some operators that are prefix, which means they
precede their operands.
– An implementation of such a computation must cause two actions: fetching the operands,
usually from memory, and executing arithmetic operations on those operands.
– operators
– operands
– parentheses
– function calls
– operator overloading
– unary -, !
– +, -, *, /, %
Conditional Expressions:
– An example:
– Precedence rules define the order in which ―adjacent‖ operators of different precedence
levels are evaluated
– Typical precedence levels
– parentheses
– unary operators
– Associativity rules define the order in which adjacent operators with the same
precedence level are evaluated
– APL is different; all operators have equal precedence and all operators associate right to
left
– Constants: sometimes a fetch from memory; sometimes the constant is in the machine
language instruction
a = 10;
Advantage: it works!
Write the language definition to demand that operand evaluation order be fixed
Overloaded Operators:
– Use of an operator for more than one purpose is called operator overloading
– Can be avoided by introduction of new symbols (e.g., Pascal‘s div for integer
division)
A narrowing conversion converts an object to a type that does not include all of the values
of the original type
– e.g., float to int
– A widening conversion converts an object to a type that can include at least
approximations to all of the values of the original type
Coercion:
– Disadvantage of coercions:
Casting:
– Examples
– C: (int) angle
Relational Operators:
– Operator symbols used vary somewhat among languages (!=, /=, .NE., <>, #)
Boolean Operators:
– Example operators
No Boolean Type in C:
postfix ++, --
&&
||
Mixed-Mode Assignment:
= can be bad when it is overloaded for the relational operator for equality
Compound Assignment:
– Example a = a + b is written as a += b
sum = ++count (count incremented, added to sum) sum = count++ (count added to sum,
incremented) Count++ (count incremented) -count++ (count incremented then negated - right-
associative)
Assignment as an Expression:
– In C, C++, and Java, the assignment statement produces a result and can be used as
operands
– An example:
While ((ch = get char ())!= EOF){…}
ch = get char() is carried out; the result (assigned to ch) is used in the condition for the while
One important result: It was proven that all algorithms represented by flowcharts can be
coded with only two-way selection and pretest logical loops
Control Structure
– A control structure is a control statement and the statements whose execution it controls
– Design question
Selection Statements
– A selection statement provides the means of choosing between two or more paths of
execution
– Two-way selectors
– Multiple-way selectors
General form:
Design Issues:
– If the then reserved word or some other syntactic marker is not used to introduce the then
clause, the control expression is placed in parentheses
– In C89, C99, Python, and C++, the control expression can be arithmetic
– In languages such as Ada, Java, Ruby, and C#, the control expression must be Boolean
Clause Form
– In many contemporary languages, the then and else clauses can be single statements or
compound statements
Nesting Selectors
– Java example
– Java's static semantics rule: else matches with the nearest if Nesting Selectors (continued)
if (count == 0) result = 0;
else result = 1;
end
• Python
if sum == 0 :
if count == 0 : result = 0
else : result = 1
Design Issues:
– Is execution flow through the structure restricted to include just a single selectable segment?
– Any number of segments can be executed in one execution of the construct (there is no
implicit branch at the end of selectable segments)
– default clause is for unrepresented values (if there is no default, the whole statement does
nothing)
– C#
Differs from C in that it has a static semantics rule that disallows the implicit execution of
more than one segment
Each selectable segment must end with an unconditional branch (goto or break)
– Ada
case expression is
when choice list => stmt_sequence; when others => stmt_sequence;] end case;
– More reliable than C‗s switch (once a stmt_sequence execution is completed, control is
passed to the first statement after the case statement
– A list of constants
– Can include:
Subranges
– Multiple Selectors can appear as direct extensions to two-way selectors, using else-if
clauses, for example in Python: if count < 10 : bag1 = True
Iterative Statements
Counter-Controlled Loops
A counting iterative statement has a loop variable, and a means of specifying the initial and
terminal, and stepsize values
Should it be legal for the loop variable or loop parameters to be changed in the loop
body, and if so, does the change affect loop control?
Should the loop parameters be evaluated only once, or once for every iteration?
FORTRAN 95 syntax
– Design choices:
The loop variable cannot be changed in the loop, but the parameters can; because they
are evaluated only once, it does not affect loop control
End Do [name]
• Design choices:
– Type of the loop variable is that of the discrete range (A discrete range is a sub-range of an
integer or enumeration type).
– The loop variable cannot be changed in the loop, but the discrete range can; it does not affect
loop control
– C-based languages
– The expressions can be whole statements, or even statement sequences, with the
statements separated by commas
– The value of a multiple-statement expression is the value of the last statement in the
expression
– If the second expression is absent, it is an infinite loop
Design choices:
– The first expression is evaluated once, but the other two are evaluated with each iteration
Design issues:
– Pretest or posttest?
– Should the logically controlled loop be a special case of the counting loop
statement or a separate statement?
C and C++ have both pretest and posttest forms, in which the control expression
can be arithmetic:
Java is like C and C++, except the control expression must be Boolean (and the body can
only be entered at the beginning -- Java has no goto
Sometimes it is convenient for the programmers to decide a location for loop control
(other than top or bottom of the loop)
Simple design for single loops (e.g., break)
Design issues for nested loops
Should the conditional be part of the exit?
Should control be transferable out of more than one loop?
– Perl has a built-in iterator for arrays and hashes, foreach Unconditional Branching
Guarded Commands
Designed by Dijkstra
Purpose: to support a new programming methodology that supported verification
(correctness) during development
Basis for two linguistic mechanisms for concurrent programming (in CSP and Ada)
Basic Idea: if the order of evaluation is not important, the program should not specify one
•Form
...
–If none are true, it is a runtime error Selection Guarded Command: Illustrated
Loop Guarded Command
Form
...
Basic Definitions:
– A subprogram header is the first line of the definition, including the name, the kind of
– The parameter profile of a subprogram is the number, order, and types of its parameters
– The protocol of a subprogram is its parameter profile plus, if it is a function, its return
type
– A subprogram declaration provides the protocol, but not the body, of the subprogram
– A formal parameter is a dummy variable listed in the subprogram header and used in the
subprogram
– An actual parameter represents a value or address used in the subprogram call Statement
– Positional
– Keyword
– parameter‘s names
----
– Referencing Environments
Disadvantages:
– Allocation/deallocation time
– Indirect addressing
Parameters and Parameter Passing: Semantic Models: in mode, out mode, inout mode
Conceptual Models of Transfer:
Implementation Models:
– Pass-by-value
– Pass-by-result
– Pass-by-value-result
– Pass-by-reference
– Pass-by-name
– in mode
– out mode
Disadvantages:
– In both cases, order dependence may be a problem procedure sub1(y: int, z: int);
...
sub1(x, x);
Pass-By-Name Example 2
inout mode
Disadvantages:
Slower accesses can allow aliasing: Actual parameter collisions: sub1(x, x); Array element
collisions: sub1(a[i], a[j]); /* if i = j */ Collision between formals and globals Root cause of all of
these is: The called subprogram is provided wider access to non locals than is necessary
Pass-by-value-result does not allow these aliases (but has other problems!)
Pass-By-Name multiple modes By textual substitution ,Formals are bound to an access method at
the time of the call, but actual binding to a value or address takes place at the time of a reference or
assignment
Resulting semantics:
If actual is an expression with a reference to a variable that is also accessible in the program,
it is also like nothing else
y := 2;
x := 2;
y := 3;
end;
y := x;
k := 5;
z :=x; end;
sub1(k+1, j, i);
Disadvantages of Pass-By-Name
C++: Like C, but also allows reference type parameters, which provide the efficiency of
pass-by- reference with in-mode semantics
Ada
All three semantic modes are available If out, it cannot be referenced If in, it cannot be
assigned Java Like C++, except only references
ALGOL 60 and most of its descendants use the runtime stack Value—copy it to the stack;
references are indirect to the stack Result—sum, Reference—regardless of form, put the address
in the stack
Name:
Run-time resident code segments or subprograms evaluate the address of the parameter
Called for each reference to the formal, these are called thunks Very expensive, compared to
reference or value-result
Simple variables are passed by copy (valueresult) Structured types can be either by copy
or reference This can be a problem, because Aliasing differences (reference allows aliases, but
value-result does not) Procedure termination by error can produce different actual parameter
results Programs with such errors are ―erroneous‖
C and C++
Programmer is required to include the declared sizes of all but the first subscript in the
actual parameter , This disallows writing flexible subprograms Solution: pass a pointer to the
array and the sizes of the dimensions as other parameters; the user must include the storage
mapping function, which is in terms of the size
Ada
... END
– Efficiency
– One-way or two-way
– Efficiency => pass by reference is fastest way to pass structures of significant size Also,
functions should not allow reference Parameters
Early Pascal and FORTRAN 77 do not Later versions of Pascal, Modula-2, and
FORTRAN 90 do Ada does not allow subprogram parameters C and C++ - pass pointers to
functions; parameters can be type checked
Possibilities:
Overloading
An overloaded subprogram is one that has the same name as another subprogram in
the same referencing environment C++ and Ada have overloaded subprograms built-in, and
users can write their own overloaded subprograms
Generic Subprograms
– A subprogram that takes a generic parameter that is used in a type expression that describes
the type of the parameters of the subprogram provides parametric polymorphism
– Independent compilation is compilation of some of the units of a program separately from the
rest of the program, without the benefit of interface information
– Separate compilation is compilation of some of the units of a program separately from the rest
of the program, using interface information to check the correctness of the interface between the
two parts
Language Examples:
– C++ and Java: like C, but also allow classes to be returned Accessing Nonlocal
Environments
The nonlocal variables of a subprogram are those that are visible but not declared
in the subprogram Global variables are those that may be visible in all of the
subprograms of a program
FORTRAN COMMON
The only way in pre-90 FORTRANs to access nonlocal variables Can be used to share
data or share storage Static scoping
External declarations: C
– Globals are created by external declarations (they are simply defined outside any function)
– Declarations (not definitions) give types to externally defined variables (and say they are
defined elsewhere)
– Dynamic Scope:
Coroutines:
Coroutine is a subprogram that has multiple entries and controls them itself Also called
symmetric control A coroutine call is named a resume. The first resume of a coroutine is to its
beginning, but subsequent calls enter at the point just after the last executed statement in the
coroutine. Typically, coroutines repeatedly resume each other, possibly forever. Coroutines
provide quasiconcurrent execution of program units (the coroutines) Their execution is
interleaved, but not overlapped
Abstraction:
Encapsulation:
– Original motivation:
– FORTRAN 90, C++, Ada (and other contemporary languages) - separately compliable
modules
Definitions: An abstract data type is a user-defined datatype that satisfies the following two
conditions:
Definition 1: The representation of and operations of objects of the type are defined in a
single syntactic unit; also, other units can create objects of the type.
Definition 2: The representation of objects of the type is hidden from the program units
that use these objects, so the only operations possible are those provided in the type's definition.
– Unit level
– Program level
Categories of Concurrency:
1. It involves a new way of designing software that can be very useful--many real-world
situation involve concurrency
Def: A task is a program unit that can be in concurrent execution with other program units
When a program unit starts the execution of a task, it is not necessarily suspended
When a task‘s execution is completed, control may not return to the caller
Def: A task is disjoint if it does not communicate with or affect the execution of any other task
in the program in any way Task communication is necessary for synchronization
Parameters
Message passing
– Kinds of synchronization:
Cooperation
Task A must wait for task B to complete some specific activity before task A can
continue its execution
Competition
When two or more tasks must use some resource that cannot be simultaneously used ., a
shared counter. A problem because operations are not atomic
Runnable or ready - ready to run but not currently running (no available
processor)
Running
Blocked - has been running, but cannot not continue (usually waiting for some
event to occur)
In sequential code, it means the unit will eventually complete its execution
Technique: Attach two SIGNAL objects to the buffer, one for full spots and one for empty spot
Methods of Providing Synchronization:
Semaphores
Monitors
Message Passing
– Semaphores can be used to implement guards on the code that accesses shared data structures
– Semaphores have only two operations, wait and release (originally called P and V by Dijkstra)
– Semaphores can be used to provide both competition and cooperation synchronization
The buffer is implemented as an ADT with the operations DEPOSIT and FETCH as the
only ways to access the buffer.
– The semaphore counters are used to store the numbers of empty spots and full spots in
the buffer
– DEPOSIT must first check empty spots to see if there is room in the buffer
– If there is room, the counter of empty spots is decremented and the value is inserted
- If there is a full spot, the counter of full spots is decremented and the value is
removed
– If there are no values in the buffer, the caller must be placed in the queue of full spots
– The operations of FETCH and DEPOSIT on the semaphores are accomplished through
two semaphore operations named wait and release wait (aSemaphore)
Put the caller in aSemaphore‘s queue Attempt to transfer control to some ready task (If the
task ready queue is empty, deadlock occurs) end
release(aSemaphore)
if aSemaphore‘s queue is empty then Increment aSemaphore‘s counter
else
Put the calling task in the task ready queue Transfer control to a task from aSemaphore‘s queue
end
SHOW the complete shared buffer example - Note that wait and release must be atomic!
Evaluation of Semaphores:
– Misuse of semaphores can cause failures in competition synchronization e.g., The program
will deadlock if the release of access is left out.
The idea: encapsulate the shared data and it operations to restrict access
A monitor is an abstract data type for shared data show the diagram of monitor buffer operation,
Concurrent Pascal is Pascal + classes, processes (tasks), monitors, and the queue data
type (for semaphores)
Example language: Concurrent Pascal (continued) processes are types Instances are statically
created by declarations
An instance is ―started‖ by init, which allocate its local data and begins its
execution
– Access to the shared data in the monitor is limited by the implementation to a single
process at a time; therefore, mutually exclusive access is inherent in the semantic
definition of the monitor
– Multiple calls are queued
Cooperation is still required - done with semaphores, using the queue data type and the
built-in operations, delay (similar to send) and continue (similar to release)
delay takes a queue type parameter; it puts the process that calls it in the specified queue and
removes its exclusive access rights to the monitor‘s data structure
Differs from send because delay always blocks the caller
continue takes a queue type parameter; it disconnects the caller from the monitor, thus freeing
the monitor for use by another process.
It also takes a process from the parameter queue (if the queue isn‘t empty) and starts it,
Differs from release because it always has some effect (release does nothing if the queue is empty)
Java Threads
– A run method code can be in concurrent execution with other such methods
The Thread class has several methods to control the execution of threads
The yield is a request from the running thread to voluntarily surrender the processor
The sleep method can be used by the caller of the method to block the thread
The join method is used to force a method to delay its execution until the run method
of another thread has completed its execution
Thread Priorities
– A thread‗s default priority is the same as the thread that create it.
– If main creates a thread, its default priority is NORM_PRIORITY
Cooperation synchronization in Java is achieved via wait, notify, and notifyAll methods
– All methods are defined in Object, which is the root class in Java, so all objects inherit them
– The notify method is called to tell one waiting thread that the event it was waiting has
happened
– The notifyAll method awakens all of the threads on the object‗s wait list
C# Threads
– Creating a thread does not start its concurrent execution; it must be requested through the Start
method
– A thread can be made to wait for another thread to finish with Join
Synchronizing Threads
– Three ways to synchronize C# threads
– The Interlocked class
– Used when the only operations that need to be synchronized are incrementing or decrementing
of an integer
When an exception occurs, control goes to the operating system, where a message
is displayed and the program is terminated
Programs are allowed to trap some exceptions, thereby providing the possibility
of fixing the problem and continuing. Many languages allow programs to trap input/ output
errors (including EOF) Definition 1:
Definition 2: The special processing that may be required after the detection of an exception
is called exception handling
A language that does not have exception handling capabilities can still define, detect, raise,
and handle exceptions
– Alternatives:
Send an auxiliary parameter or use the return value to indicate the return status of
a Subprogram
Pass a label parameter to all subprograms (error return is to the passed label)
e.g., FORTRAN
– How and where are exception handlers specified and what is their scope?
– Where does execution continue, if at all, after an exception handler completes its
execution?
– Should there be default exception handlers for programs that do not provide their own?
Continuation
– Some built-in exceptions return control to the statement where the exception was
raised
– Others cause program termination
– User-defined exceptions can be designed to go to any place in the program that is
labeled
Those that are enabled by default but could be disabled by user code
Those that are disabled by default but could be enabled by user code
Those that are always enabled
Evaluation
The design is powerful and flexible, but has the following problems:
– Dynamic binding of exceptions to handler makes programs difficult to write and to read
– The continuation rules are difficult to implement and they make programs hard to read
Based on logic and declarative programming 60‘s and early 70‘s, Prolog (Programming in
logic, 1972) is the most well known representative of the paradigm.
– Specially designed for theorem proof and artificial intelligence but allows
general purpose computation.
– Some other languages in paradigm: ALF, Frill, G¨odel,, Mercury, Oz, Ciao,
_Prolog, datalog, and CLP languages
A logic program clause is a clause with exactly one positive literal 8(A _ ¬A1 _¬A2... _ ¬An)
_8(A ( A1 ^ A2... ^ An)
Proof: by refutation, try to un satisfy the clauses with a goal clause G. Find 9(G). Linear
resolution for definite programs with constraints and selected atom. CLP on first
order terms. (Horn clauses). Unification. Bidirectional. Backtracking. Proof search
based on trial of all matching clauses
Atoms:
– Numbers
Variables:
[a-zA-Z 0-9]*
Structures:
Starts with an atom head have one or more arguments (any term) enclosed in parenthesis,
separated by comma structure head cannot be a variable or anything other than atom.
a(b) a(b,c) a(b,c,d) ++(12) +(*) *(1,a(b)) ‘hello world‘(1,2) p X(b) 4(b,c) a() ++() (3) × some
structures defined as infix:
Prolog interpreter automatically maps some easy to read syntax into its actual
structure. List: [a,b,c] _ .(a,.(b,.(c,[])))
String: "ABC" _ [65,66,67] (ascii integer values) use display (Term). to see actual structure of
the term
Unification:
p1(arg1, arg2, ...) :- p2(args,...) , p3(args,...) .means if p2 and p3 true, then p1 is true. There can
be arbitrary number of (conjunction of) predicates at right hand side.
p(arg1, arg2, ...) .sometimes called a fact. It is equivalent to: p(arg1, arg2, ...) :- true.
p(args) :- q(args) ; s(args) .
Lists Example:
– second list starts with first list prefix of ([],). Prefix of ([X|Rx], [X|Ry]) :- prefix of (Rx,Ry).
– second list contains first list Sublist (L1,L2) :- prefix of (L1,L2). Sublist (L,[|R]):-
sublist(L,R).
For goal clause all matching head clauses (LHS of clauses) are kept as backtracking
points (like a junction in maze search) Starts from first match. To prove head predicate, RHS
predicates need to be proved recursively. If all RHS predicates are proven, head predicate is
proven. When fails, prolog goes back to last backtracking point and tries next choice. When no
backtracking point is left, goal clause fails. All predicate matches go through unification so goal
clause variables can be instantiated.
operators (is) force arithmetic expressions to be evaluated all variables of the operations needs
to be instantiated.
is operator forces RHS to be evaluated: X is Y+3*Y Y needs to have a numerical value when
search hits this expression. Note that X is X+1 is never successful in Prolog. Variables are
instantiated once.
The design of the imperative languages is based directly on the von Neumann architecture
Efficiency is the primary concern, rather than the suitability of the language for software
development.
The design of the functional languages is based on mathematical functions
A solid theoretical basis that is also closer to the user, but relatively unconcerned with the
architecture of the machines on which programs will run
Mathematical Functions:
Def: A mathematical function is a mapping of members of one set, called the domain set, to
another set, called the range set.
A lambda expression specifies the parameter(s) and the mapping of a function in the
following form f(x) x * x * x for the function cube (x) = x * x * x functions.
– Lambda expressions are applied to parameter(s) by placing the parameter(s) after the
expression
Functional Forms:
Def: A higher-order function, or functional form, is one that either takes functions as
parameters or yields a function as its result, or both.
1. Function Composition:
A functional form that takes two functions as parameters and yields a function whose
result is a function whose value is the first actual parameter function applied to the result of the
application of the second Form: h(f )° g which means h (x) f ( g ( x))
2. Construction:
A functional form that takes a list of functions as parameters and yields a list of the results
of applying each of its parameter functions to a given parameter
Form: [f, g]
3. Apply-to-all:
A functional form that takes a single function as a parameter and yields a list of
values obtained by applying the given function to each element of a list of parameters
Form:
For h (x) =x * x * x
LISP –
LISP is the first functional programming language, it contains two forms those are:
1. Data object types: originally only atoms and lists
The objective of the design of a FPL is to mimic mathematical functions to the greatest
extent possible. The basic process of computation is fundamentally different in a FPL than
in an imperative language
In an imperative language, operations are done and the results are stored in variables for
later use
Management of variables is a constant concern and source of complexity for imperative
programming
In an FPL, variables are not necessary, as is the case in mathematics
In an FPL, the evaluation of a function always produces the same result given the same
parameters
This is called referential transparency
A Bit of LISP:
– Originally, LISP was a type less language. There were only two data types, atom and list
– Lambda notation is used to specify functions and function definitions, function applications,
and data all have the same form.
E.g :,
- The first LISP interpreter appeared only as a demonstration of the universality of the
computational capabilities of the notation
Scheme:
–A mid-1970s dialect of LISP, designed to be cleaner, more modern, and simpler version than
the contemporary dialects of LISP, Uses only static scoping
– Functions are first-class entities, They can be the values of expressions and elements of lists,
They can be assigned to variables and passed as parameters
Primitive Functions:
QUOTE is required because the Scheme interpreter, named EVAL, always evaluates
parameters to function applications before applying the function. QUOTE is used to
avoid parameter evaluation when it is not appropriate
QUOTE can be abbreviated with the apostrophe prefix operator e.g., '(A B) is
equivalent to (QUOTE (A B))
CAR takes a list parameter; returns the first element of that list
CONS takes two parameters, the first of which can be either an atom or a list and the
second of which is a list; returns a new list that includes the first parameter as its first
element and the second parameter as the remainder of its result
LIST - takes any number of parameters; returns a list with the parameters as elements
Note that if EQ? is called with list parameters, the result is not reliable Also, EQ? does not
work for numeric atoms
– NULL? takes one parameter; it returns #T if the parameter is the empty list; otherwise ()
Note that NULL? returns #T if the parameter is ()
– Lambda Expressions
– Form is based on notation e.g.,
EX:
(DEFINE pi 3.141593)
(DEFINE two_pi (* 2 pi))
EX:
ML :
A static-scoped functional language with syntax, that is closer to Pascal than to LISP
Uses type declarations, but also does type inferencing to determine the types of
undeclared variables
It is strongly typed (whereas Scheme is essentially type less) and has no type coercions
Includes exception handling and a module facility for implementing abstract data types
Includes lists and list operations
The val statement binds a name to a value (similar to DEFINE in Scheme)
Function declaration form: fun function_name (formal_parameters)
=function_body_expression; e.g., fun cube (x : int) = x * x * x;
Functions that use arithmetic or relational operators cannot be polymorphic--those
with only list operations can be polymorphic
o APL is used for throw-away programs o LISP is used for artificial intelligence
o Knowledge representation
o Machine learning
o Natural language processing
o Modeling of speech and vision
Scheme is used to teach introductory
– Functional Languages:
o Simple semantics
o Simple syntax
o Inefficient execution
Scripting languages
Pragmatics
In such a system, the script is said to glue the sub systems together
– Economy of expressions
PYTHON
– Readability is better
– Powerful interpreter
– PYTHON has a limited repertoire of primitive types: integer, real, and complex
Numbers.
– Its boolean values (named False and True) are just small integers.
Primitive values and strings are immutable; lists, dictionaries, and objects are mutable; tuples
are mutable if any of their components are mutable
and assert break class continue def del elif else except exec finally for from global if
import in is lambda not or pass print raise return try while yield
Python is a dynamically typed language. Based on the value, type of the variable is
during the execution of the program.
Python (dynamic)
C=1
C = [1,2,3]
C(static)
Weakly vs. strongly typed python language differs in their automatic conversions.
Perl (weak)
$b = `1.2` $c
= 5 * $b;
Python (strong)
b =`1.2` c= 5* b;
– Within a procedure we may initialize local variables and define local procedures.
In python, variables defined inside the function are local to that function. In order to change them
as global variables, they must be declared as global inside the function as given below.
S=1
Def myfunc(x,y); Z = 0
Global s; S = 2
Procedural abstraction
– The only difference is that a function procedure returns a value, while a proper
procedure returns nothing.
Since PYTHON is dynamically typed, a procedure definition states the name but not the type of
each formal parameter.
Python procedure
Eg :Def gcd (m, n): p,q=m,n while
p%q!=0: p,q=q,p%q return q
Data Abstraction
– PYTHON has three different constructs relevant to data abstraction: packages ,modules ,
and classes
– A Class is a group of components that may be class variables, class methods, and instance
methods.
– A procedure defined in a class declaration acts as an instance method if its first formal
parameter is named self and refers to an object of the class being declared. Otherwise the
procedure acts as a class method.
– Each module must explicitly import every other module on which it depends
– When that module is first imported, it is compiled and its object code is stored in a file
named program.pyc
– The PYTHON compiler does not reject code that refers to undeclared identifiers. Such code
simply fails if and when it is executed
– The compiler will not reject code that might fail with a type error, nor even code that will
certainly fail, such as:
Module Library
– PYTHON is equipped with a very rich module library, which supports string handling,
markup, mathematics, and cryptography, multimedia, GUIs, operating system services,
internet services,compilation, and so on.
– Unlike older scripting languages, PYTHON does not have built-in high-level string
processing or GUI support, so module library provides it