Title: Programming Languages
1ProgrammingLanguages
CSCI-4430 CSCI-6969April 29, 2008
- David Goldschmidt, Ph.D.
- Computer Science
- The College of Saint Rose
2Diversity of Computer Systems
- As a critical part of our society,computer
systems are increasinglycomplex - Such systems require a myriadof programming
languages
3Language Evaluation Criteria
- How do you evaluate a programming language?
- Goals of language
- Readability
- Writability
- Reliability (of language)
- Portability
- Cost (, training costs, compilation process)
- Ease of maintenance (of compilers and source code)
4Von Neumann Architecture
- Imperative Languages
- Data and programs are stored in memory
- Variables mimic memory
- Assignment statements
- Arithmetic operations
- Iterative repetition
5Language Categories
- Imperative languages
- Evolved from the von Neumann architecture
- Focus on variables, assignment and arithmetic
statements, and iterative constructs - e.g. C, C, Pascal, C, Java, Visual BASIC,
Perl, JavaScript, Ruby, etc. - Additional languages
- Visual languages, Scripting languages, Web-based
languages
6Language Categories
- Object-oriented languages
- Evolved out of imperative languages
- Data abstraction, inheritance, polymorphism,late
binding - e.g. C, Java, C, Smalltalk, Eiffel
- Markup languages
- Web-based or application-specific markup
languages specify layout of Web pages, database
schemas, etc. - e.g. XHTML, XML, XSLT, MathML, RDF, etc.
7Language Categories
- Functional languages
- Apply (often recursive) functions to parameters
- Often an interpretive language
- e.g. LISP, Scheme
- Logic languages
- Rule-based approach to building a knowledge base
- Perform queries against knowledge base
- e.g. Prolog (also Semantic Web)
8Compiled Languages
9Lexical Analysis
- Lexical analyzer is a pattern matcher
- Identifies and isolates lexemes
- Lexemes are lexical units orlogical substrings
of the sourceprogram that belong together - Lexical analyzer assigns internalcodes called
tokens to the lexemes - e.g. sum is lexeme IDENT is token
10Lexical Analysis
- Example assignment statement
- Write down the lexemes and tokens ofthe above
statement
result sum value / 100
Token IDENTIFIER ASSIGNMENT_OPERATOR IDENTIFIER SU
BTRACTION_OPERATOR IDENTIFIER DIVISION_OPERATOR IN
TEGER_LITERAL SEMICOLON
Lexeme result sum value / 100
11Lexical Analysis Implementation
- How do we implement a lexical analyzer?
- Design state transition diagrams that
describethe tokens and write a program to
implement thecorresponding state machine - Use a table to implement the state machine
- Write a formal description of the token patterns
ofthe language and use lex (or another software
tool)to generate a lexical analyzer
12Syntax Analysis
- Syntax analysis portion of a language processor
usually consists of two components - Low-level part called a lexical analyzer
- A finite automaton based on aregular grammar
- High-level component calleda syntax analyzer or
parser - A push-down automaton based ona context-free
grammar or BNF
13Syntax Analysis i.e. Parsing
- What are the goals of a parser?
- Find all syntax errors
- For each syntax error, produce a diagnostic error
message - Produce the parse tree for the program
and recover...
14Backus-Naur Form
ltprogramgt ? begin ltstmtsgt end ltstmtsgt ? ltstmtgt
ltstmtgt ltstmtgt ltstmtgt ? ltvargt ltexprgt ltvargt ? a
b c d ltexprgt ? lttermgt lttermgt lttermgt -
lttermgt lttermgt ? ltvargt literal-integer-value
15Derivations
- A derivation is a repeated application of rules
- Starts with the start symbol and ends with a
sentence - Many (often infinite!) possible derivations
ltprogramgt gt begin ltstmtsgt end gt begin
ltstmtgt end gt begin ltvargt ltexprgt end
gt begin b ltexprgt end gt
begin b lttermgt lttermgt end gt begin
b ltvargt lttermgt end gt begin b c
lttermgt end gt begin b c 12 end
16ltassigngt ? ltvargt ltexprgt ltvargt ? A B C
D ltexprgt ? ltexprgt ltexprgt ltexprgt
ltexprgt ( ltexprgt ) ltvargt
Parse Trees
- A parse tree shows the structure of a derivation
- Every internal node is a non-terminal abstraction
- Every leaf node isa terminal symbol
ltassigngt
17Ambiguous Grammars
- A grammar that generates a sentential form for
which there are two or more distinct parse
treesis an ambiguous grammar - Ambiguity in a grammar leads to problems....
- Compilers often base semanticson parse trees
- e.g. operator precedence, if-else
18Unambiguous Grammars
ltassigngt ? ltvargt ltexprgt ltvargt ? A B C
D ltexprgt ? ltexprgt ltexprgt ltexprgt
ltexprgt ( ltexprgt ) ltvargt
ltassigngt ? ltvargt ltexprgt ltvargt ? A B C
D ltexprgt ? ltexprgt lttermgt
lttermgt lttermgt ? lttermgt ltfactorgt
ltfactorgt ltfactorgt ? ( ltexprgt ) ltvargt
19Top-Down Parsers
- Most common top-down parsing algorithms
- A recursive-descent parser is coded based on the
BNFor EBNF description of the language - An LL parser uses a table-driven implementation
- LL algorithms
- First L specifies a left-to-right scan of the
input - Second L specifies a leftmost derivation is
generated
20LL Algorithms
- Limitations of top-down LL parsers
- Requires pairwise disjointness, the ability to
determine the correct RHS on the basis of only
one token of lookahead
21Pairwise Disjointness Test
- If pairwise disjointness is not present,
problemcan often be resolved via left factoring - e.g.
- (also possible to resolve by replacing with an
EBNF rule)
ltvargt ? identifier identifier ltexprgt
22Extended BNF ? EBNF
- Extended BNF (EBNF) increases the readability and
writability of BNF - Optional parts of RHS
- Without EBNF, this requires two rules
ltselectiongt ? if ( ltexprgt ) ltstmtgt else ltstmtgt
23Extended BNF ? EBNF
- Extended BNF (EBNF) increases the readability and
writability of BNF - Repeatable parts of RHS (repeat 0 or more times)
- Without EBNF, this requires recursion and two
rules
ltident_listgt ? ltidentifiergt , ltidentifiergt
24Extended BNF ? EBNF
- Extended BNF (EBNF) increases the readability and
writability of BNF - Multiple-choice parts of RHS
- Without EBNF, this requires three rules
lttermgt ? lttermgt ( / ) ltfactorgt
25Recursive-Descent Parsers
- A recursive-descent parser consists offunctions
for each non-terminal orabstraction within the
grammar - Each function implements its non-terminal
- i.e. it parses the language generated byits
associated non-terminal - Functions are often recursive or call other
functionsin a manner that descends the grammar
26Recursive-Descent Parsers
- Given the EBNF below
- Goal is to write functions for each
non-terminal.... - Because EBNF minimizes the number of
non-terminals, EBNF is well-suited for
recursive-descent parsers
ltexprgt ? lttermgt (-) lttermgt lttermgt ? ltfactorgt
(/) ltfactorgt ltfactorgt ? id ( ltexprgt )
27ltexprgt ? lttermgt (-) lttermgt lttermgt ? ltfactorgt
(/) ltfactorgt ltfactorgt ? id ( ltexprgt )
Recursive-Descent Parsers
- Parsing the expression belowyields the trace to
the right - And the parse tree below
gt lex() returns a Enter ltexprgt Enter
lttermgt Enter ltfactorgt gt lex() returns Exit
ltfactorgt Exit lttermgt gt lex() returns b Enter
lttermgt Enter ltfactorgt gt lex() returns EOF Exit
ltfactorgt Exit lttermgt Exit ltexprgt
a b
28LL Algorithms
- Limitations of top-down LL parsers
- Cannot handle direct left recursion
- A recursive-descent parser subprogram for A calls
itself to parse the first symbol (A) of the RHS
calls itself again and again and again.... - A grammar can be modified to remove left recursion
A ? A B B
29Bottom-Up Parsing
- Unlike top-down parsing,bottom-up parsing can
handle left recursion - e.g.
- Example derivation
E ? E T T T ? T F F F ? ( E ) id
id id id
30Bottom-Up Parsing
- Given a right sentential form a,determine the
substring of a thatforms the RHS of a rule
thatproduces the previous sentential form inthe
rightmost derivation
E ? E T T T ? T F F F ? ( E ) id
E gt E T gt E T F gt E T id gt E
F id gt E id id gt T id id gt F
id id gt id id id
31LR Parsers
- Most common bottom-up parsing algorithmsare LR
Parsers - The L specifies a left-to-right scan of the input
- The R specifies a rightmost derivation
- LR parsers typically implemented using
arelatively small program and a parsing table - e.g. Unix tool coupled with lex called yacc
(yet another compiler compiler)
32LR Parsers
- LR parsers are table-driven
- Action table specifies the action of the parser
giventhe parser state and the next token - Goto table specifies which state to put on top of
the parse stack after a reduce action is performed
33LR Parsers
- E ? E T
- E ? T
- T ? T F
- T ? F
- F ? ( E )
- F ? id
34LR Parsers
- Advantages of using LR parsers
- LR parsers work for nearly all grammarsthat
describe programming languages - LR parsers work on a larger class of
grammarsthan other bottom-up algorithms - And are equally efficient
- LR parsers detect syntax errors as soon as its
possible - LR parsers support a class of grammars thats a
superset of the class of grammars parsable by LL
parsers
35Attribute Grammars
- Context-free grammars (CFGs) such as BNF cannot
describe all programming language syntax - e.g. type compatibility ( possible, but lengthy)
- e.g. a variable must be declared before being
used - An attribute grammar extends a CFG
- e.g. carry type information (or other static
semantics) across the parse tree
36Attribute Grammars Example
37Attribute Grammars Example
- Consider valid sentence
- Avoid ambiguity in yoursemantic rules by
usingnumeric subscripts
real A int B A A B
A A B
38Attribute Grammars Example
- Compute the attribute values of the parse tree(a
process called decorating the tree)
real A int B A A B
- ltvargt.actual_type ? look-up(A) rule 4
- ltexprgt.expected_type ? ltvargt.actual_type rule
1 - ltvargt2.actual_type ? look-up(A) rule
4ltvargt3.actual_type ? look-up(B) rule 4 - ltexprgt.actual_type ? int or real rule 2
- ltexprgt.expected_type ltexprgt.actual_type rule
2
39Attribute Grammars Example
40Attribute Grammars Example
41Operational Semantics
- Use operational semantics to describe the meaning
of a program by translating it into a simpler
language (and execute via a virtual machine) - Changes in state (e.g. memory, registers,
etc.)define the meaning of the statement
for (expr1 expr2 expr3) ...
42Binding
- A binding is a semantic association in a program
- Data type of count is bound to int at compile
time - Memory address of count is bound at run time
- The meaning of the assignment () and addition
() operators are bound at compile time
int count 15 count count 5
43Static Binding
- A binding is static if it occurs before run time
and remains unchanged throughout program
execution - Defining constants
- Binding variables to theirrespective data types
const int Q 15 // C/C const double PI
3.1415927
public static final int JACK 11 //
Java public static final int QUEEN 12 public
static final int KING 13
int count, x, y, z // C/C char letter double
radius, area, volume
44Static Binding
- A binding is static if it occurs before run time
and remains unchanged throughout program
execution - Static code (e.g. Java)
public static void main(String args)
System.out.println("Do something.") int y
calculate(10) public static int calculate(int
x) return x x x
45Dynamic Binding
- A binding is dynamic if it occurs during run time
or can change throughout program execution - Variable binding toa memory address
- (can be static, too)
- Binding a value toa variable
- Dynamic memory allocation
char c, d, e // C/C int count, x, y,
z double radius, area, volume
char c 'Q' // C/C count 5 radius
47.556
char cptr // C/C cptr (char
)malloc(SIZE)
46Dynamic Binding
- A binding is dynamic if it occurs during run time
or can change throughout program execution - Object creation
public class Fraction // Java public
static final int ZERO 0 public static final
int ONE 1 private double numerator
private double denominator public double
toDecimal() return numerator /
denominator
47Explicit Declaration
- An explicit declaration is a program
statementthat declares the data type of a
variable
/ C/C/Java / int count char letter double
radius double area double circumference
48Implicit Declaration
- An implicit declaration is a mechanism for
specifying data types of variables based on their
first appearance - e.g. JavaScript
x 47 // numbers r 14.45 PI
3.1415927 y 'Welcome' // strings z
"Welcome" name "Shirley Ann" done true
// boolean valid false enough (x gt 35)
49Lifetimes of Variables
- The lifetime of a variable is the time during
whichit is bound to a particular memory location - Variables begin their lifetimeupon declaration
- Variables end their lifetimewhen they go out of
scope - or when the program endsexecution....
/ C/C/Java / int count 100 while (count
gt 0) int xyz / ... / count--
50Lifetimes of Variables
- Memory is allocated from a pool of available
memorywhen the variable is first bound - Memory is deallocated whena variable ends its
lifetime - The allocated memory isgiven back to the pool
- Categories of Variables by Lifetime
- Static
- Stack-Dynamic
- Explicit Heap-Dynamic
- Implicit Heap-Dynamic
51Static Variables
- Static variables are bound to memory locations
before run time - And remain bound to thesame memory
locationthroughout execution - e.g. FORTRAN 77
- e.g. C static variables
- Sneaky global variables?
52Stack-Dynamic Variables
- Stack-dynamic variables are variables whose
storage bindings are created during run time when
their declaration statements are elaborated - e.g. variables defined in methods in Java,
C, C
main() / C / int x ... while (f gt
0) int q 0 ...
53Explicit Heap-Dynamic Variables
- Explicit heap-dynamic variables are nameless
variables whose storage bindings are allocated
(and deallocated) during run time at the
discretion of the programmer - Use pointers and references variables to access
- e.g. dynamic objects in C, objects in
Java, use of malloc() in C
String name // Java name new
String("Hi.") name null // optional
int x // C x new int delete x //
avoid memory leaks!
int x / C / x (int )malloc(sizeof(int
))
54Implicit Heap-Dynamic Variables
- Implicit heap-dynamic variables are variables
whose storage bindings are allocated (and
deallocated)only when they are assigned values - Names that adapt tohowever they are used
- e.g. variables in APL, strings and arrays
in Perl and JavaScript (and hashes in
Perl)
// JavaScript numbers 5, 7, 9, 11 numbers
"Hello." numbers 100
Perl q2mapping ( "April" gt 30,
"May" gt 31, "June" gt 30
) q2mapping ( "q2" gt 4000 )
55Scope
- Variable scope defines the range of
statementsover which a variable is visible - Local variables of a program unit X are variables
thatare declared within X and therefore visible
within X - Non-local variables of a program unit X are
variablesthat are visible but not declared
within X
56Static Scope
- Static scope indicates that the scope of a
variablecan be determined before execution - How?
- Search local declarations first,then search in
increasinglylarger enclosing scopes, untila
valid declaration is found - Variable x becomes hidden
- Not valid in Java or C
main() / C / int x 5
printf("d\n", x) int x 10 int y
20 printf("d\n", x) int x
15 int z 20 printf("d\n", x)
57Static Scope
- Static scope indicates that the scope of a
variablecan be determined before execution - JavaScript and PHP do not support nested static
scopes
var abc false if ( s "HELLO" ) abc
true var abc 500 document.write("abc is "
abc) document.write("abc is still " abc)
58Symbol Tables
- A symbol table acts as a dictionary, mapping
namesto semantic information - Variable names and constants
- Type or class names
- Subprogram names
- i.e. procedures, functions, methods, etc.
- Compilers use symbol tables to keep track of
names instatically scoped programs
59Symbol Tables LeBlanc-Cook Implementation
- LeBlanc and Cook approach to symbol tables
- All names are added to a hash table
- Keyed by name
- Each scope, as its encountered,is assigned a
unique integer - Scope 0 pervasive outermost scope (e.g.
predefined identifiers) - Scope 1 programmer-declared global names
- etc.
60type T record F1 integer F2
real end var V T ... module M import
V export I var I integer
procedure P1 (A1 real A2 integer)
real begin ... end P1 procedure P2
(A3 real) var I integer begin
... with V do ... end ...
end P2 ... end M
Symbol Tables
61Symbol Tables
scope
type T record F1 integer F2
real end var V T ... module M import
V export I var I integer
procedure P1 (A1 real A2 integer)
real begin ... end P1 procedure P2
(A3 real) var I integer begin
... with V do ... end ...
end P2 ... end M
I
I
I
62Python
- Python is
- an imperative language
- a functional language
- an object-oriented language
- Python uses an interpreter and a virtual machine
- Therefore, Python is available on many platforms
63Python
gtgtgt 3 3 gtgtgt a 15 gtgtgt a 3 45 gtgtgt b
'Hello.' gtgtgt b Hello. gtgtgt b 3 'Hello.Hello.Hello
.' gtgtgt a b gtgtgt b 3.1415927 gtgtgt a Hello.
- Python is dynamically typed
- Concise, flexible, writable
- Create objects implicitly
- (or use cached objects)
- Python maintains a list of names,which reference
objects - Assignment statements change object references
- Objects have a reference count, a type, and a
scope
64Python Scoping Rules
- Python names are both dynamically boundand
statically scoped - Binding of name to object (and therefore
type)occurs during run time - Scope can be determined before program execution
- Functions define a local scope
- Modules define a global scope (i.e. a file-level
scope) - Global variables are attributes of a module X
when X is imported elsewhere
65Python Sequences
gtgtgt L1 2, 3, 5 gtgtgt L1 2, 3, 5 gtgtgt L10
1 gtgtgt L1 1, 3, 5 gtgtgt L2 L1 gtgtgt L22 7 gtgtgt
L2 1, 3, 7 gtgtgt L1 1, 3, 7 gtgtgt L1-1 7 gtgtgt
L102 1, 3 gtgtgt L11 3, 7 gtgtgt L2 L1
- Python supports lists and tuples
- Lists are mutable
- Tuples ( ) are immutable
- Obtain slices of lists byoptionally specifying
leftand right bounds - Copy a list using this
66Python Sequences
gtgtgt T1 (2, 3, 5) gtgtgt T1 (2, 3, 5) gtgtgt T10
1 ...error text... gtgtgt len(T1) 3 gtgtgt T1 (8,
13) (2, 3, 5, 8, 13) gtgtgt T10 2 gtgtgt T1
(8) ...error text... gtgtgt T1 (8,) (2, 3, 5,
8) gtgtgt T1 (8,) gtgtgt T1 (2, 3, 5, 8)
- Python supports lists and tuples
- Lists are mutable
- Tuples ( ) are immutable
- Tuples are immutable, so createnew tuples by
concatenatingexisting tuples together - Python is strongly typed
67Python Sequences
gtgtgt L1 14, 12, 19 gtgtgt L1.sort() gtgtgt L1 12,
14, 19 gtgtgt L2 "c", "a", "h" gtgtgt
L2.sort() gtgtgt L2 'a', 'c', 'h' gtgtgt T1 (14,
12, 19, 17, 8) gtgtgt L3 list(T1) gtgtgt
L3.sort() gtgtgt L3 8, 12, 14, 17, 19 gtgtgt T1
tuple(L3) gtgtgt T1 (8, 12, 14, 17, 19)
- Lists can be sorted
- Convert lists to tuples,and vice versa
- Use list(x) to createa new list based on x
- Use tuple(x) to createa new tuple based on x
68Python Strings
gtgtgt S1 'hi' gtgtgt S2 "how's life?" gtgtgt print
S21 ow's life? gtgtgt S2.upper() "HOW'S
LIFE?" gtgtgt print \ ... """longer text ... with
newlines ... goes here""" longer text with
newlines goes here gtgtgt a 45 gtgtgt b 13 gtgtgt
print S1 a b ...error text... gtgtgt print S1, a
b hi 58
- Python supports strings asimmutable sequences
- Use single, double, ortriple-quoting
- Use the comma , operatorto print different data
types - Use list slicing and specificstring object
methods
69Python Classes
- Object-oriented programming in Python
- is optional
- defines new abstract data types called classes
- enables creation of run time objects
- supports both inheritance and multiple
inheritance - supports operator overloading (increases
writability) - supports polymorphism
- the semantics of a method dependon the object(s)
being operated on
70Abstraction
- Abstraction Xis a view or representationof
entity X that includes only themost significant
attributes of X - Abstractions combat program complexity
- Abstraction X may be a subset of X oralso
introduce a new interface
71Process Abstraction
- Nearly all programming languagessupport process
abstraction with subprograms,functions, methods,
etc. - Hide implementation details
// e.g. Java double result calculate( x1, x2
) ...
public static double calculate( double x1, double
x2 ) // ... calculate and return a double
// ... implementation details here ...
72Data Abstraction in Java
- Java is similar to C, except
- All user-defined types are classes
- i.e. no structs
- Java also supports pure abstractions called
interfaces - All objects are allocated from the heap
andaccessed through reference variables - Individual entities in classes have access
control modifiers (private or public) rather than
clauses
73Data Abstraction in Java
class Stack private int stack private
int maxLen, topIndex public Stack() //
default constructor stack new int100
maxLen 99 topIndex -1 public
void push(int number) ... public int
pop() ... public int peek() ...
public boolean isEmpty() ...
Stack s // reference variable s new
Stack() s.push(21) s.push(18) System.out.print(
s.pop()) ...
74Data Abstraction in Java
- Use static to define methods that are available
without creating an instance of an object - e.g. Math.random(), System.out.println(), etc.
- Omit static to define instance methods that are
available only after an object is instantiated - Circle c1 new Circle(12.5)
- double area c1.getArea()
75Java Garbage Collection
- Objects that are no longer referenced are garbage
- The Java Virtual Machine ( JVM ) automatically
performs garbage collection - Frees up memory used by garbage
- Usually sufficient to allow JVM to
performgarbage collection at its own pace - To force garbage collection on an object,assign
its reference variable to null - Can also try calling System.gc()
76Object-Oriented Programming
- Object-oriented programming is aprogramming
paradigm that combines - Abstract data types
- Inheritance (a.k.a. generalization)
- Dynamic binding (a.k.a. polymorphism)
- Languages often provide OOP in addition to
procedural and other language constructs
77Inheritance
- UML diagram representing Generalization
- Children classes are more specific
- Parent classes are more general
78Polymorphism
- The Substitutability Principle
- Given an inheritance relationship, we can use
achild element anywhere the parent is expected - We can use the morespecific element anywherethe
more general elementis expected
79Polymorphism
- Polymorphism allows you to send the same message
to different classes (and the objects respond
appropriately)
Canvas
r1.draw()
r1Rectangle
c2.draw()
c2Circle
c3.draw()
c3Circle
80Dynamic Binding
- Polymorphism is achieved via dynamic binding
- More specifically, dynamically bind messagesto
method definitions at run time - Based on class hierarchies
- Advantages and disadvantages
- Has the advantage of being easily extensible
- Improves writability of reusable methods
- Key disadvantage is run time performance
81Functional Language Design
- The design of imperative languages is based
directly on the von Neumann architecture - Efficiency is a primary concern
- Variables have memory locations
- The design of functional languages is based
directly on mathematical functions - A solid theoretical basis more natural to users
- Minimally concerned with machine architecture
82Lambda Expressions
- A lambda expression specifies the parametersand
the mapping expression of a function - Nameless function
- During evaluation, parameter x is bound to
aparticular member of the domain
?(x)x x x
83Lambda Expressions
- The lambda expression is the function itself
- Apply the expression to a parameter
?(x)x x x
(?(x)x x x)(2)
84Lambda Expressions
- Lambda expression may use multiple parameters
?(x, y)x y
85Scheme
- Scheme was developed (MIT, 1970s) to be a
cleaner,more modern, and simpler version of LISP - Scheme uses static scoping
- LISP dialects use either static or dynamic
scoping - Scheme uses an interpreter
- Literals evaluate to themselves
- Expressions are evaluated using EVAL
86Atoms and Lists
- An atom is a single symbol (an identifier) or a
numeric literal (e.g. A, 12, x, y, n, etc.) - A list is a group of zero or more atoms or lists
- Lists are specified using surrounding parentheses
- A simple list consists of only atoms
- A nested list consists of atoms and lists
(A B C D E F G H I J)
(A (B C D) E F (G H (I J)))
87LISt Processing Functions
- CONS constructs a list by prependingthe first
parameter to the second - LIST constructs a list with all parameters
aselements applies to zero or more parameters - APPEND constructs a list by combining
theelements of all lists into one
88LISt Processing Functions
- CAR obtains the first elements of a list
- CDR obtains a list of the elements that
remainafter skipping the first element of a list - CADR (and other combinations) apply CAR and CDR
(CADR '(a b c d)) (CADDR '(a b c d))
89Proper and Improper Lists
- A list is a series of pairs
- i.e. CAR and CDR
- A pairs CDR refers tothe next pair
- Given list L
- if the CDR of the last pair is (), the list is
proper - otherwise, the list is an improper list
- Improper lists are written as dotted pairs
(a . b)
(a b . c)
90Scope in Scheme
- Use let or let to bind names to values
- e.g. use let to bind names x and y to values 4
and 6 - Names x and y only in scope in last parameter (
x y) - Use let to activate scope immediately
(define x 2) (let ((x 4) (y x)) ( x y))
(let ((x 4) (y x)) ( x y))
91Logic Programming Prolog
- The design of logic programming languages
isbased on formal logic - Prolog is a goal-based logic programming language
for symbolic non-numeric computation - Prolog is a declarative language
- No flow of control....
- Apply rules to facts to produce answers to
queries - i.e. Use a logical inferencing process to produce
results - Only specifications of results are stated,not
the procedures for obtaining the results
92Propositions
- A proposition is a logical statementthat may or
may not be true - Semantics are not implied
- A proposition describes objects andrelationships
between objects
male('George').
smart('Mary').
female('Mary').
smart('George').
tall('George').
parent('Mary', 'George').
93Facts and Rules
- Specify facts and rules using a Horn clause
- Headless Horn clause no consequent
- Headed Horn clause single proposition as
consequent
parent('Mary', 'George').
mother(X, Y) ? parent(X, Y) ? female(X)
mother(X, Y) - parent(X, Y), female(X).
94Approaches to Finding a Goal
- Forward chaining (bottom-up resolution)
- Begin with facts and rules of knowledge base and
attempt to find sequence that leads to goal - Works well with small set of possibly correct
answers - Backward chaining (top-down resolution)
- Begin with goal and attempt to find sequence
thatleads to set of facts in knowledge base - More efficient approach
- Prolog implementations use backward chaining
95Handling Multiple Subgoals
- Prolog implementations use depth-first search
(dfs) approach to finding a goal consisting of
multiple subgoals - Backtracking as necessary....
- Another approach is to use a breadth-first search
(bfs),but dfs is usually preferred - to consume fewer resourcesi.e. memory
female(X), parent(X, 'Bob').
96Atoms and Variables
- Atoms consist of symbols
- Start with a lowercase letter
- Variables also consist of symbols
- Start with an uppercase letter
- An anonymous variable is the underscore character
( _ ) - Use single quotes to create an atom thatstarts
with a capital letter
a b dave next_solution
X Y N List1 P2
'Dave' 'Apple' 'Next'
97Numbers and Arithmetic
- Numbers in Prolog include integers and reals
- But Prolog is not typically used for numeric
computation - Predefined operators
- Prolog supports arithmetic evaluationvia the is
operator
- / mod
X 1 2.
X is 1 2.
distance(X,Y) - speed_mph(X,Speed),
time_minutes(X,Time), Y is Speed Time / 60.
98List Processing in Prolog
- Prolog supports list structures using square
brackets and commas - Prolog also supports CAR and CDR constructs
apple, prune, orange, grape
Head_of_List Rest_of_List
99The Study of Programming Languages
- Why study programming languages?
- Required course...
- More tools in your programming toolbox
- Increased capacity to express ideas
- Increased ability to learn new languages
- Increased ability to build efficient software
systems
100Final Exam Coverage
FINAL EXAM Wednesday (5/7) 3-6pm in DCC 318
- Final Exam on Wednesday 5/7
- Chapters 1-6, 11, 12, 15, 16
- (not 3.5, 5.7, 6.5-6.9, 11.5, 12.4, 12.8,
15.8) - Topics
- Lexical analysis, lexemes
- Syntax analysis, (E)BNF, derivations, parse trees
- Semantics, attribute grammars, operational
semantics - Symbol tables, LeBlanc-Cook Implementation
- Python
- Functional languages, list processing, Scheme
- Logic programming, inference chains, Prolog
open book, open notesno computers, cell phones,
calculators, etc.