+ All Categories
Home > Documents > CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Date post: 22-Dec-2015
Category:
View: 219 times
Download: 1 times
Share this document with a friend
Popular Tags:
71
CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann
Transcript
Page 1: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

CS 330Programming Languages

12 / 05 / 2006

Instructor: Michael Eckmann

Page 2: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Today’s Topics• Questions / comments?• Scheme assignment posted --- due 12/13 by 5pm.• Scheme

– map & apply

– optional parameters

• Discuss the points made in the Hughes paper

• Logic Languages / Chap. 16

Page 3: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Map

• map

– a function that takes two parameters which are a function and a list

– map applies the function to each element of the list and returns a list of the returned values

– the following returns (#t #t #t #f #f #f #f #t)

– (map number? '(1 2 3 a b r tttt 4.5))

– another example:

– (map floor '(1 2 3 4 4.5 4.6 7.8))

Page 4: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Apply

• apply

– a function that takes two parameters which are a function and a list

– it applies the function to all elements of the list and returns whatever the function would have returned if called using those elements of this list as individual parameters.

– only functions that take a collection of arguments, not as a list, individually (like + and <) can be passed to apply

– (apply < '(3 4 5 1)) ; ok, because (< 3 4 5 1) is a valid call.

– (apply + '(4 5 6 7)) ; ok, because (+ 4 5 6 7) is a valid call.

Page 5: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Example

(define (mapApply fun lis) (map (lambda (lamlis) (apply fun lamlis)) lis))

• What does this do?

• How/why does it work?

Page 6: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

optional parameters

• A function that takes optional parameters is specified in this way:

(define (fun reqp1 reqp2 . optparms)

; reqp1 is required

; reqp2 is required

; optparms will be a list of all the rest of the arguments passed in

)

; if you want a function with only optional parameters:

(define (fun2 . optparms)

; optparms will be a list of all the arguments passed in

)

Page 7: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

How about writing avg ...;; write a function named avg which takes in any number of numbers as parameters and

averages them.

;; how will I write the parameters when defining the function?

;; how will we handle the parameters inside the function?

;; can we use anything we just learned to allow us to write the code inside the function?

(define (avg )

)

Page 8: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

How about writing avg ...;; write a function named avg which takes in any number of numbers as parameters and

averages them.

;; how will I write the parameters when defining the function?

;; how will we handle the parameters inside the function?

;; can we use anything we just learned to allow us to write the code inside the function?

(define (avg . nums )

(cond

((null? nums) 0) ; returns 0 as the average of no nums

(else (/ (apply + nums) (length nums))))

)

Page 9: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Learning FLs• There are enough people who believe, even

though Scheme is not widely used, the way of thinking that is required to program in a FL like Scheme is a worthwhile skill for a computer scientist.

• “LISP is worth learning for a different reason — the profound enlightenment experience you will have when you finally get it. That experience will make you a better programmer for the rest of your days, even if you never actually use LISP itself a lot. “ - ESR (Eric S. Raymond)

Page 10: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Paper• What were the main points of the paper?• Was it convincing?• Why or why not?

Page 11: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Paper• Let's see reduce as a Scheme function.

• This link shows how to get lazy evaluation in Scheme

• http://www.cs.auc.dk/~normark/prog3-03/html/notes/eval-order_themes-delay-stream-section.html

Page 12: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

example of using let and (read); add up all the numbers; entered via user input until -1 is entered(define (addnums) (let ((inp (read))) (cond ((= inp -1) 0) (else (+ inp (addnums))) ) ) )

Page 13: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

begin• begin lets you execute expressions in order (in

sequence). The return value is the value of the last expression. This is used to sequence expressions that have side-effects like I/O, or assignments like set!, to make sure they are done in order.

e.g.

(begin

expr1

expr2

...

exprn

)

Page 14: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

begin• Another use of begin is within an if. Since an if

is of the form:

(if predicate then_expression else_expression )

• If your then_expression needed to be more than one expression you could use a begin.

• Many scheme forms have implicit begins to sequence the expressions.

Page 15: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Final comments on Scheme.• Anything further you'd like to ask/discuss about Scheme?

Page 16: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Reading• You probably should have already read chapter 15 by

now.• I suggest reading chapter 16 to keep up with the next few

lectures starting now.

Page 17: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Logic (or Declarative) languages

– Express programs in a form of symbolic logic– Produce results via logical inferences

• Logic programs– specify the desired results– instead of creating the procedures (or functions) to

produce them

• Since we are writing no procedures, the syntax of logic languages are quite different from imperative (e.g. C, C++, Java) or even Functional (e.g. LISP, Scheme)

Page 18: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Prolog is the only widely used Logic Programming

Language• Logic languages are based on formal logic

– Like the axiomatic semantics we saw when we dealt with semantic and correctness proofs

– Recall the weakest precondition computations we did

Page 19: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Symbolic logic can be used for the basic needs of formal

logic:– express propositions (defined on next slide)– express relationships between propositions– describe how new propositions can be inferred from

other propositions• Particular form of symbolic logic used for logic

programming called predicate calculus

Page 20: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Some terminology

– Proposition --- logical stmt that may or may not be true • The statement consists of objects and relations between

terms.– Terms are either constants or variables

– Atomic proposition --- consist of compound terms

– Compound term – one element of a mathematical relation --- looks like mathematical function notation with names and parentheses.

• Two parts are:– Functor– Ordered list of parameters

Page 21: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Compound term

– The compound terms are also called tuples. 1-tuples, 2-tuples, 3-tuples, 4-tuples ...

• Depending on the number of parameters• Compound term examples:

student(jon)

like(seth, OSX)

like(nick, windows)

like(jim, linux)

• The meaning of the relations are up to the programmer.

Page 22: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• The meaning of the relations are up to the programmer.• For instance

– like(jim, linux) • Could mean jim likes linux. Or it could mean jim is

similar to linux. Or it could mean something else entirely.

• There is no intrinsic semantics.

• If the relations are named well though, the programs obviously become more readable.

Page 23: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logical connectors

a implies b

b implies a

a b

a b

implication

a is equivalent to b

a bequivalence

a or ba bdisjunction

a and ba bconjunction

not a anegation

MeaningExampleSymbolName

Page 24: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Logical operators

– Conjunction (and) is like intersection among sets.– Disjunction (or) is like union among sets.

• Implication– a implies b can be read as "if a, then b"

Page 25: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Precedence:

• Negation• Conjunction, Disjunction, Equivalence• Implication

Page 26: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• So far we've seen only constants in these propostions• To use a variable in a propostion we need to preface it

with either “for all” or “there exists”• These are quantifiers

– For all is represented by an upside-down A– There exists is represented by a backwards E

• Predicate calculus consists of the logical connectors we just saw in addition to the two quantifiers above.

Page 27: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages•For Predicate Calculus, (that is using the logical connectors and the quantifiers) it should be obvious that there are many ways to state the same thing•Anyone want to give an example?

Page 28: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages•That is why we use a standard form for propositions•Clausal form:

B1 B2 … Bn A1 A2 … Am

means if all the As are true, then at least one B is true•Antecedent: right side•Consequent: left side

Page 29: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages•The A's and B's in the clausal form can be variables or constants. •When they are variables, the “for all” quantifier is implied.•Note: the meaning of variable here is different than the meaning we associate with variables in imperative languages.•We can use clausal form exclusively because:– All predicate calculus propositions can be

algorithmically converted to clausal form. So, we do not lose generality by restriction to this form of propostions.

Page 30: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Some examples:

C A B

ForAll X.(mammal(X) dog(X))

ThereExists X.(father(bob,X) female(X))

–Taken separately, read each of the above in English.

Page 31: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Logic Languages• Some examples:

C A B

if both A and B are true, then C is true.

ForAll X.(mammal(X) dog(X))All dogs are mammals

ThereExists X.(father(bob,X) female(X))bob has a daughter

Page 32: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Predicate Calc and proving theorems• A use of propositions is to discover new theorems that can

be inferred from known axioms and theorems• Resolution: an inference principle that allows inferred

propositions to be computed from given propositions• A simple example:older(joanne, jake) mother(joanne, jake)wiser(joanne, jake) older(joanne, jake)

A new propostions can be constructed from resolution: wiser(joanne, jake) mother(joanne, jake)

Page 33: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Predicate Calc and proving theorems• The presence of variables in propostions requires

resolution to find values for those variables that allow the matching process to succeed. This is called unification.

• Instantiation is the temporary assigning of values to variables.

• During some more complex resolutions, assigning some temporary values might cause the matching process to fail, at which time, backtracking must occur to instantiate a different value to the variable.

Page 34: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Predicate Calc and proving theorems• One possible way to prove a theorem is by contradiction.• Make a proposition that is the theorem negated.• The theorem is then attempted to be proved by finding an

inconsistency.

• This is a theoretically useful way to prove theorems, but in practice the time it takes might be too long.

• Theorem proving is the basis for logic programming so we need a faster way for it to be able to do it.

Page 35: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Predicate Calc and proving theorems• A restricted kind of clausal form is used when

propositions are used for resolution. These special kinds of propostions are Horn clauses

– Only 2 forms– A single atomic proposition on left side– Or– Empty left side

• Left side is called the head. If left side is not empty the Horn clause is called a headed Horn clause.

• Anyone recall what an atomic proposition is?

Page 36: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Predicate Calc and proving theorems• An atomic propostion is a functor and a set of parameters

in parentheses. e.g. mother(joanne, jake)• A headed Horn clause example:

older(joanne, jake) mother(joanne, jake)these state relationships among relations

• What do you think the purpose of headless Horn clauses might be? e.g. mother(joanne, jake)

• Not all (but most) propositions can be stated as/converted to Horn clauses.

Page 37: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Overview of Logic Programming• Logic programming semantics is Declarative semantics

– There is a simple way to determine the meaning of each statement

– Simpler than the semantics of imperative languages• In imperative the semantics of a simple assignment

statement is complex as it depends on scoping rules, determining types and values of variables, etc. --- sometimes depends on run-time context.

– In logic programming the semantics of a statement is quite simple. The statement itself contains all that is needed to be known.

Page 38: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Overview of Logic Programming• Logical programming is nonprocedural

– Programs do not state how a result is to be computed, but rather the form of the result

• We don't tell the computer how to get a result. Instead we state the form of the result and assume the computer can determine how to get that result.

• We provide the relevent information via the predicate calculus. And the computer infers the results using resolution.

Page 39: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Overview of Logic Programming

• Describe the characteristics of a sorted list, not the process of rearranging a list

sort(old_list, new_list) permute (old_list, new_list) sorted (new_list)

sorted (list) ForAll j such that 1 j < n, list(j) list (j+1)

• This says that if a list is in non-decreasing order, it is sorted. Also, if the old_list is a permutation of the new_list and the new_list is sorted, then that's what it means to sort an old_list to be the new_list

Page 40: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog

• Our text uses the Edinburgh Syntax version of Prolog• Term: a constant, variable, or structure• Constant: an atom or an integer• Atom: symbolic value of Prolog• Atom consists of either:

–a string of letters, digits, and underscores beginning with a lowercase letter

–a string of printable ASCII characters delimited by apostrophes

Page 41: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog

• Variable: any string of letters, digits, and underscores beginning with an uppercase letter

• Instantiation: binding of a variable to a value– Lasts only as long as it takes to satisfy one complete

goal• Structure: represents atomic proposition

functor(parameter list)

Page 42: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Fact statements

– Headless Horn clausesstudent(jonathan).brother(tyler, cj).

• Rule statements

– Headed Horn clauses

– Right side: antecedent (if part)

• May be single term or conjunction

– Left side: consequent (then part)

• Must be single term

• Conjunction: multiple terms separated by logical AND operations (implied)

Page 43: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prologparent(kim,kathy):- mother(kim,kathy).

• Can use variables (universal objects) to generalize meaning:

parent(X,Y):- mother(X,Y).sibling(X,Y):- mother(M,X), mother(M,Y), father(F,X), father(F,Y).

Page 44: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• GOAL STATEMENTS• For theorem proving, a theorem is in the form of a proposition

that we want the system to prove or disprove

• Same format as headless Hornstudent(james)

• this asks if james is a student, it either fails (james is not a student) or it doesn't (james is indeed a student)

• Conjunctive propositions and propositions with variables are also legal goals

father(X,joe)

• this asks for all fathers of joe, if any, otherwise it fails.

Page 45: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• INFERENCING• Queries are called goals• If a goal is a compound proposition, each of the facts is a

subgoal• To prove a goal is true, the system must find a chain of

inference rules and/or facts. For goal Q:

B :- AC :- B…Q :- P

• Process of proving a subgoal is called matching, satisfying, or resolution

Page 46: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• POSSIBLE WAYS TO INFER• Bottom-up resolution, forward chaining

– Begin with facts and rules of database and attempt to find sequence that leads to goal

– works well with a large set of possibly correct answers• Top-down resolution, backward chaining

– begin with goal and attempt to find sequence that leads to set of facts in database

– works well with a small set of possibly correct answers• Prolog implementations use backward chaining

Page 47: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• POSSIBLE WAYS TO INFER• When goal has more than one subgoal, can use either

– Depth-first search: find a complete proof for the first subgoal before working on others

– Breadth-first search: work on all subgoals in parallel

• Prolog uses depth-first search– Can be done with fewer resources so it is preferred for

use in Prolog

Page 48: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Backtrack during inference• For a goal with multiple subgoals, if fail to show truth of

one of subgoals, reconsider previous subgoal to find an alternative solution: backtracking

• Begin search where previous search left off• Can take lots of time and space because may find all

possible proofs to every subgoal

Page 49: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• So, when trying to prove a goal, Prolog uses

– backward chaining (starting at goal) to try to find facts that satisfy it

– depth first seach when satisfying a chain of subgoals– backtracking during inference to possibly get an

alternative solution to an earlier subgoal

Page 50: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Prolog also supports integer variables and integer arithmetic

• is operator: takes an arithmetic expression as right operand and variable as left operand

• A is B / 10 + C

• Not the same as an assignment statement!

• B & C must have been instantiated and A must not have been instantiated for that expression to have A take on the value of the expression.

• But if A is instantiated prior to this expression or B or C are not instantiated, then the clause is not satisfied and no instantiation can take place.

• Example: Sum is Sum + Number.

Page 51: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prologspeed(ford,100).

speed(chevy,105).

speed(dodge,95).

time(ford,20).

time(chevy,21).

time(dodge,24).

distance(X,Y) :- speed(X,Speed),time(X,Time),Y is Speed * Time.

% in Visual Prolog 5.2, use an = instead of is

• Here, the facts are the first six statements and the last is a rule stating the relationship between time, speed and distance.

• Example query: distance(chevy, Chevy_Distance)

• Chevy_Distance is instantiated with the value 2205

Page 52: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• TRACE• (not available in Visual Prolog 5.2, but exists in other

implementations of Prolog.) Still worth discussing to show the order of execution.

• Tracing model of execution - four events:– Call (beginning of attempt to satisfy goal)– Exit (when a goal has been satisfied)– Redo (when backtrack occurs)– Fail (when goal fails)

Page 53: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prologlikes(jake,chocolate).

likes(jake,apricots).

likes(darcie,licorice).

likes(darcie,apricots).

trace.

likes(jake,X),

likes(darcie,X).

This is asking, what is X such that both jake and darcie like X

Let's trace it on the board.

Page 54: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• List Structures are another basic data structure in Prolog

besides atomic propositions.• A List is a sequence of any number of elements• Elements can be atoms, atomic propositions, or other

terms (including other lists)

[apple, prune, grape, kumquat][] (empty list)[X | Y] (head X and tail Y)

Page 55: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• [X | Y] (head X and tail Y)

• Head X is like Scheme's car of a list• Tail Y is like Scheme's cdr of a list• | can be used to dismantle a list into head and tail in

query mode• | can be used to construct a list from a head and a tail

Page 56: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• [X | Y] (head X and tail Y)

– my_list([apple, prune, grape]).

– my_list([apricot, peach, pear, lime]).

• These signify that the lists are new elements of the relation my_list. Just like parent(jane). stated that jane is an element of the relation parent.

• my_list is not a variable --- it is a relation.

• Example query:

– my_list([ My_head | My_tail ] )

– Results in my_head instantiated with apple, and my_tail instantiated with [prune, grape]

Page 57: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• [X | Y] (head X and tail Y)

– my_list([apple, prune, grape]).– my_list([apricot, peach, pear, lime]).– my_list([ My_head | My_tail ] )

• If this query was part of a goal and it backtracked, the next value for my_head would be: apricot and the next value for my_tail would be: [peach, pear, lime]

Page 58: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• [X | Y] (head X and tail Y)

– also used for constructing lists

• Construction example:– [apricot, peach | [pear, lime]]

Page 59: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Append

– The first two parameters to append are appended together to produce the result which parameter 3 gets instantiated with.

append([], List, List).

append([Head | List_1], List_2, [Head | List_3])

:- append (List_1, List_2, List_3).

• Order matters! The termination step (the headless clause) is first (just like in Scheme.) The recursion step is second. Prolog will try to match the propositions in order because it uses depth-first search.

• How do we read these propositions?

Page 60: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prologappend([], List, List).

append([Head | List_1], List_2, [Head | List_3])

:- append (List_1, List_2, List_3).

• So it says, if the first parameter is the empty list, the resulting list (parameter 3) is instantiated to the value of the second parameter.

• Otherwise, list3 is list1 and list2 appended together if the head of the first parameter is the head of parameter 3 (the result) and the tail of the 3rd parameter is the tail of the 1st parameter appended to the second parameter.

• Or in other words: appending [Head | List_1] to List_2 results in [Head | List_3] only if, List_3 is List_1 appened to List_2.

• It'll become clearer with an example.

Page 61: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Similar to scheme's:

(cons (car list1) (append (cdr list1) list2))

append([], List, List).

append([Head | List_1], List_2, [Head | List_3])

:- append (List_1, List_2, List_3).

append([bob, jo], [jake, darcie], Family).

Let's trace through on the board how Prolog will instantiate Family. (page 681.)

Page 62: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• As stated earlier, Prolog uses depth-first search and left-to-right

evaluation. So, resolution problems can occur with recursion that is not tail recursion.

• ORDER OF PROPOSITIONS AND SUBGOALS MATTER

• Example:

ancestor(X, X).

ancestor(X, Y) :- ancestor(Z, Y), parent(X, Z).

• Problem because second proposition has 1st subgoal same as proposition (left-recursion). Suppose it is given the query ancestor(mike, jane). It goes to ancestor(Z, jane) and instantiates Z with a value. Then it does the proposition again to determine if it is true ...

• Just like the problem a recursive descent parser has (remember?)

• How to solve this?

Page 63: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Example:

member(Element, [Element | _ ] ).

member(Element, [ _ | List] ) :- member(Element, List).

/*

_ is anonymous variable, use when we won't use the variable in the proposition.

*/

These member propositions state that if first parameter is the head of the second parameter, then member is satisfied. If not, then Element is a member of the List if Element is in the tail of the List.

Page 64: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Cut (!) to prevent backtracking (to earlier subgoals before the cut during a

resolution.)

• Recall, that prolog backtracks when a goal (or subgoal) fails.

• Let's say we have something like this on the right hand side of a proposition:

– member(X, Lis), do_something(X, Lis, Y).

• If member is satisfied and then do_something is attempted and fails, backtracking will occur and cause member to be reattempted. Inside member's implementation, it will pick up where it left off and possibly not find another match. To make sure it doesn't backtrack, we can use the Cut.

member(Element, [Element | _ ] ) :- !.

member(Element, [ _ | List] ) :- member(Element, List).

• Now, Prolog cannot backtrack to reevaluate member once Element is found in the list.

Page 65: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Explain what cut does.

Page 66: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Negation problem

parent(bill, jake).

parent(bill, shelly).

sibling( X, Y) :- parent(M, X), parent(M, Y).

• goal

sibling(X, Y).

results in:

• X = jake

• Y = jake

• Because it goes through the facts first with parent(M, X) and instantiates them to bill and jake. Then parent(M,Y) starts at the beginning of the facts and tries to find a fact with bill as parent. It finds bill and jake again.

Page 67: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Negation problem solution

parent(bill, jake).

parent(bill, shelly).

sibling( X, Y) :- parent(M, X), parent(M, Y), X <> Y.

• goal

sibling(X, Y).

results in:

• X = jake

• Y = shelly

• Because it goes through the facts first with parent(M, X) and instantiates them to bill and jake. Then parent(M,Y) starts at the beginning of the facts and tries to find a fact with bill as parent. It finds bill and jake again. But then X <> Y becomes jake <> jake which fails, so backtracking occurs to parent(M, Y). Prolog remembers where it left off in the list of parent facts, so it gets the next one (bill, shelly) that's good, so then X <> Y becomes jake <> shelly which is satisfied. Done.

Page 68: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Prolog• Fail• Can be used (as a subgoal) to force a goal to fail, thus

forcing backtracking.• Only makes sense as the last subgoal of a goal (because

any subgoals after it would never get tested.)

Page 69: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Visual Prolog• Programs have the following sections:

– DOMAINS• Used when you want to declare your own “types”• Standard types are: char, byte, short, ushort, word,

integer, unsigned, long, ulong, dword, real, string, symbol

– PREDICATES (relation declarations)• States the relation name and types.• e.g.: son(string, string).

– CLAUSES (facts and rules section)

– GOAL (query)

Page 70: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Visual Prolog• Let's look at a couple of programs I have ready to show

you.

– speed calculation based on time, distance

– factorial

– list example

Page 71: CS 330 Programming Languages 12 / 05 / 2006 Instructor: Michael Eckmann.

Michael Eckmann - Skidmore College - CS 330 - Fall 2006

Visual Prolog• A few other things:

– use nl to output a new line

– use write( ) to write strings, variables, etc.

– use exit to exit from a program.

– use readln(Var) to read input from keyboard into Var (can use any name starting with a capital letter for the variable)

• Let's look at a couple of programs I have ready to show you.

– speed calculation based on time, distance

– factorial

– list example


Recommended