prolog programming - 11334
TRANSCRIPT
Introduction toProlog Programming
Slide no: 2
History The first, official version of prolog
was developed at the university of Marseilles, France by Alain Colmerauer in the early 1970s as a tool for programming in logic.
Slide no: 3
History Today, prolog is an important tool in
programming artificial intelligence applications and in the development of customized knowledge bases, expert systems, natural language interfaces, and smart information management systems.
Visual prolog addresses the same target market as SQL database systems, C++ development systems and other language tools like visual basic, Borland's Delphi, or IBM's visual age.
Slide no: 4
Applications of Prolog intelligent data base retrieval natural language understanding expert systems specification language machine learning robot planning automated reasoning problem solving
4
Slide no: 5
How Does Prolog Differ From Other Languages
Prolog is a declarative language.This means that given the necessary facts and
rules, prolog will use deductive reasoning to solve your programming problems.
In a procedural language, the programmer must provide step by step instructions that tell the computer exactly how to solve a given problem.
Prolog is “intelligent.” Prolog has a built-in inference engine
performing a top-down, left to right search in fact and rules to find solutions.
Slide no: 6
How Does Prolog Differ From Other Languages
Prolog programs origins from mathematical proof-theory. A prolog program can be viewed as a
specification of the problem. SWI-Prolog is an open
source implementation of the programming language Prolog. SWI-Prolog is widely used in research and education as well as for commercial applications.
Slide no: 7
Predicate logic was developed to easily convey logic-based ideas into a written form.
In predicate logic: 1. eliminate all unnecessary words from
your sentences. 2. transform the sentence, placing the
relationship first and grouping the objects after the relationship. The objects then become arguments that the relationship acts upon.
7
Slide no: 8
Facts: What Is Known
Facts are like relations in Database systems, representing the known data.
Bill likes Cindy.Cindy likes Bill.Bill likes dogs.
In Prologlikes(bill, cindy).likes(cindy, bill).likes(bill, dogs).
Slide no: 9
Rules: What You Can Infer from Given Facts
Natural Language
Cindy likes everything that Bill likes.Caitlin likes everything that is green.
Prolog
likes(cindy, Something):- likes(bill, Something).likes(caitlin, Something):- green(Something).
• We call “likes” for a predicate
• A predicate has a name and an arity
• Like has two arguments ( arity=2 )
Read as IF
Slide no: 10
More About Rules This first example shows a rule that can
be used to conclude whether a menu item is suitable for Diane.
In Prolog, a relationship like this must be represented by a rule because the conclusion is based on facts.
Slide no: 11
Here's another example:
This natural language relationship can be conveyed in Prolog with the following rule:
This rule shows the following relationship:
Slide no: 12
Variables
Variables start with an uppercase letter or underscore.
VALID Variables My_first_correct_variable_name _MyFirstQuarter Sales_10_11_86
INVALID Variables 1stattempt second attempt "disaster"
Slide no: 13
The usage of Variable’s
Prolog has no assignment statement
Variables in Prolog get their values by being unified with values.
Until it gets a value, a variable is said to be free; when it gets a value, it becomes bound.
When backtracking; variables becomes free again.
Variables are used as part of the pattern-matching, process, not as a kind of information storage.
Slide no: 14
Anonymous Variables Can be used in place of any other variable Never get set to a value
14
male(bill).male(joe).female(sue).female(linda).parent(bill, joe).parent(sue, joe).parent(joe, tammy).
Query:
?- parent(Parent, _).
Slide no: 15
Anonymous variables can also be used in facts. The following Prolog facts
could be used to express the natural language statements
15
Slide no: 16
Searching for the solution’slikes(ellen,reading).likes(john,computers).likes(john,badminton).likes(leonard,badminton).likes(eric,swimming).likes(eric,reading).
Consider this query: Is there a person who likes both reading and swimming?
likes(Person, reading), likes(Person, swimming).
The solutions are found through Searching, Matching/Unification and Backtracking
Slide no: 17
Queries: True/False
In natural language, we ask you:Does Bill like Cindy?
In Prolog syntax, we ask Prolog:?- likes(bill, cindy).
Given this query, Prolog would answeryes
Slide no: 18
Queries, getting answersWe could ask you in natural language:
What does Bill like?
In Prolog syntax, we ask Prolog:?- likes(bill, What).
Prolog will return What=cindyWhat=dogs
Slide no: 19
Comments
/* This is an example of a comment */
% This is also a comment
/***************************************//* and so are these three lines *//***************************************/
/*You can also nest a comment /*within a comment*/ like this */
Slide no: 20
Prolog concepts Unification
passing parameters, dealing with assignment, case selection, etc.
Search principles searching for success (or failure) top-down, left to right
Backtracking providing multiple solutions non-determisme, determinism and cut
Recursion Lists - and other compound objects.
Slide no: 21
Unification Unification means making two objects
“identical.” Unification is performed when a goal (or
subgoal) is matched against a suitable fact or left hand side of a rule. (Expressed procedurally: when a procedure call is executed, it is matched with the suitable procedure definition).
Unification is made between. The 1st parameter in the goal (sub-goal). And 1st parameter in the fact/rule-head.
If it succeeds, unification continues with the remain pairs from left to right.
Unification is fully recursive.
Slide no: 22
Unification and matchingIdentical values match each other;
parent(joe,tammy) matches parent(joe,tammy).
A Free Variable can match with any value;
parent(joe,X) matches parent(joe,tammy)
A bound variable matched only with the value it is bound toX =tammy, parent(joe,X) matches parent(joe,tammy)
Two free variables unifies each other;
parent(joe,X) matches parent(joe,Y)
Slide no: 23
Unification Examples
object 1 unified with object 2 example result
constant free var. 4 X X=4
bound variable free variable X Y Y gets the value of X
free variable bound variable X Y X gets the value of Y
bound variable constant X “b” fails if X has a value different then “b”
compound object compound object f(X,Y) f(2,3) X=2, Y=3
compound object compund object f(q(2,X),3) f(P,3) succeds if P is free, and P=q(2,X) . (.. more posibilities )
compund object compound object f(3,X) q(3,X) fails, due to different functors
Slide no: 24
Giving input to a predicate
domains mydom = i(integer); s(string)
predicates procedure wr(mydom) - (i)
clauses wr(i(Int)):- write("Was integer: ",Int). wr(s(Str)) :- write("Was String: ",Str).
GOAL wr(i(88)).
Passing input to the predicate
The variable will be bound to 88
Procedure means no fail!
Only input flow accepted!
Case/switch statement!
Slide no: 25
Return values
domains person = person(string Name, integer Age, string Address)
predicates procedure getname(person,string Name) - (i,o)
clauses getname(person(N,_,_),N).
GOAL getname(person("Leo",39,"Fredensborg"),Name).
Output only
N will be bound to “leo”
N has a value which it will return to Name
A comment name can be given
Slide no: 26
Unification works recursively !
domains person = person(string Name, integer Age)
predicates determ eq(person,person) determ eq(integer,integer)
clauses eq(X,X).
GOAL% eq(1,2). eq(person("leo",39),person("leo",38)).
Determ can fail !
Overloading means multiple declarations !
Slide no: 27
“=“ Means unificationdomains person = person(string Name, integer Age)
GOAL X = person("leo",39), Y = person("leo",38), X = Y.============= Or try this:GOAL X = person("leo",39), X = person(Y,Z).
Slide no: 28
Unification and calculations Visual Prolog support the most know
used mathematical functions. They can be tried out by: unifying a free variable X with various
calculations, for example GOAL X=sqrt(4)*7+1
Visual Prolog supports logical expressions like:
GOAL not(2<=4)
Slide no: 29
Disjunctions - “or” - “;”
PREDICATEScar(symbol Type,long Odometer,integer Age,symbol Color,long Price)truck(symbol Type,long Odometer,integer Age,symbol Color,long Price)vehicle(symbol Type,long Odometer,integer Age,symbol Color,long Price)
CLAUSEScar(chrysler,130000,3,red,12000).car(ford,90000,4,gray,25000).car(datsun,8000,1,red,30000).
truck(ford,80000,6,blue,8000).truck(datsun,50000,5,orange,20000).truck(toyota,25000,2,black,25000).
vehicle(Make,Odometer,Age,Color,Price):-car(Make,Odometer,Age,Color,Price);
truck(Make,Odometer,Age,Color,Price).
Slide no: 30
Conjunction’s - “and” - “,”You can get to search for a solution by setting this compound goal:
car(Make, Odometer, Years_on_road, Body, Cost), Cost < 25000.This is known as a conjunction. To fulfill this compound goal, Prolog will try to solve the subgoals in order. First, it will try to solve
car(Make, Odometer, Years_on_road, Body, Cost).
and then
Cost < 25000.
with the variable Cost referring to the same value in both subgoals. Try it out now.
Slide no: 31
Backtracking
Backtracking gives prolog the capability to find several solutions to a problem. Like searching a “maze”
Each time a fact or left-hand side of a rule is used to full-fill a goal (sub-goal), and there a more facts or rules that possible may be give solutions, prolog sets A pointer = BACKTRACK POINT Prolog can use any number of pointers
Slide no: 32
Backtracking
Predicates with several “possibilities” to search are called NON-DETERMINISTIC predicates
CUT is used to remove backtracking possibilities
Slide no: 33
Backtracking example
/* find three cards giving the value of 20 */
GOAL: card(One,Val1),card(Two,Val2),card(Thre,Val3),Val1 + Val2 + Val3 = 20.
PREDICATES nondeterm card(string,integer)CLAUSES card("ace",14). card("king",13). card("queen",12). card("knight",11). card("10",10). card("9",9). card("8",8). card("7",7). card("6",6). card("5",5). card("4",4). card("3",3). card("2",2).
Exercise:
1) type in the program and try to run the Goal above. Which solutions exists?How many pointers did Prolog use?2) use debugger to follow the search3) use cut (!) to limit the search
Slide no: 34
Fail predicateGOAL: card(One,Val1),
card(Two,Val2), card(Thre,Val3), Val1 + Val2 + Val3 = 20, write(One,” - ”,Two ,” - ”,Three),nl,fail.
Use indentation to show the backtracking possibilities!
fail works like “2=3”
Slide no: 35
top-down, left to right search
The search pattern to validate the goal p(3): p(X) is matched with its first rule, having three
new subgoals a(X), b(X) and c(X). this causes Prolog to start validate a(X). If the
search of a(X) in depths succeds, the seach continues with b(X), i.e. the search continues from left to right
CLAUSES p(Y):- a(Y), b(Y), c(Y).
a(X):- a1(X),a2(X). a(X):- a3(X).
b(X):- b1().
GOAL p(3).
p(3)
search a() in depthbefore b() and c() aresearched.
a(Y) b(Y) c(Y)
a1 a2
p(3)
as b failed Prolog backtracksto a() to try its next rulewhich are then searched indepth before b() is revisited
a(Y) b(Y) c(Y)
a3(fails)
Slide no: 36
Prolog key concepts Recursion
Recursion imagine that in a mirror in from of you, you can
see a mirror behind you - in which you see the mirror in front of you, in which..
Recursion is a very powerful programming technique. solving a little part of a problem, and then
solving a problem similar but smaller than the original -solves the original problem!
Find a route from mci to cph: start with a single flight (mci to stl) then find a route to continue (from stl to cph)
finish when a route is made up by one flight.
Slide no: 37
Factorial numbers
Factorial of 1 is 1
Factorial of N is N multiplied with factorial of N-1
PREDICATESfactorial(integer,integer)CLAUSESfactorial(1,1):-!.factorial(X,FactX):-
Y=X-1,factorial(Y,FactY),FactX = X*FactY.
Slide no: 38
The power functionX raised to the power of N: X
n
PREDICATES p(integer X, integer N, integer Result)
CLAUSES p(_,0,1):-!. p(X,1,X):-!. p(X,N,Result):-
N1 = N-1,p(X,N1,XN1),Result = X * XN1.
GOAL p(2,3,Result).
X0 = 1
X1 = X
Xn = X*X
(n-1)
Slide no: 39
last-call optimization
When:• The call is the very last subgoal of the clause.• There are no backtrack points earlier in the clause.
Here's an example that satisfies both conditions:count(N) :-
write(N), nl,NewN = N+1,count(NewN).
Slide no: 40
How Not to Do Tail Recursionbadcount1(X) :-
write('\r',X),NewX = X+1,badcount1(NewX),nl.
Slide no: 41
Another Way to Lose Tail Recursion Elimination
badcount2(X) :- write('\r',X),NewX = X+1,badcount2(NewX).
badcount2(X) :-X < 0,write("X is negative.").
Slide no: 42
Cuts to the Rescue
cutcount2(X) :-X >= 0, !,write('\r',X),NewX = X+1,cutcount2(NewX).
cutcount2(X) :-write("X is negative.").
Slide no: 43
Rewriting for tail elimination
Tail recursivefactorial(N,FactN):-
factorial(N,FactN,1,1).
factorial(N,FactN,N,FactN):-!.factorial(N,FactN,I,P):-NewI = I+1,NewP = P*NewI,factorial(N, FactN, NewI, NewP).
No recursion elimination possible
factorial(1,1):-!.
factorial(X,FactX):-Y=X-1,factorial(Y,FactY),FactX = X*FactY.
Slide no: 44
Predicate typesErroneous - Always exitfailure - Always failprocedure - Always successdeterm - succeed or failsmulti - 1 or more solutions (never fail)nondeterm - 0 or more solutions
predicates append(list,list,list)-
procedure (i,i,o),determ (i,i,i)nondeterm (o,i,i)
Slide no: 45
Prolog Key ConceptsBacktracking & Cut Cut is used to remove backtracking
possibilities. The effect of cut is accurately described as:
It is not possible to backtrack over a cut within a given rule. Instead, that rule - and the remaining facts and rules of that predicate fails.
( Possible enabling backtracking at a “higher level” in the search-tree).
Cut may be described as the “mouse-trap” predicate call.
The compiler option “check types of predicates” advice where setting a cut have an effect - and possible changes non- determinism to determinism.
Slide no: 46
Prevent Backtracking to a Previous Subgoal in a Rule
r1 :- a, b, !, c.
Examplebuy_car(Model,Color):-
car(Model,Color,Price),check_color(Color,sexy),Price < 25000,!,go_buy().
Now we are sure about the solution
Slide no: 47
Prevent Backtracking to the Next Clause
Cut when right head are matchedr(1):- ! , a , b , c.r(2):- ! , d.r(3):- ! , c.r(_):- write("This is a catchall clause.").
Cut when right clause are foundr(X) :- X = 1 , ! , a , b , c.r(X) :- X = 2 , ! , d.r(X) :- X = 3 , ! , c.
Slide no: 48
The rules for Cut Set cuts as far to the left as possible. Set only the needed cut’s. If in doubt - let the compiler assist in
spotting the right location ! A cut in the end of a clause spoils the
last-call optimization. Focus on setting the cut correctly - it
is difficult!
Slide no: 49
Cut controls the type of the predicate
predicates determ check(integer)clauses check(1):-write("one").goal check(99).
determ predicate
Slide no: 50
Setting Cut’s
predicates nondeterm check(integer)clauses check(1):-write("one"). check(_):-write("something else").goal check(99).
Now check becomes nondeterministic !
Try the goal: check(1),fail.
Slide no: 51
Cut to the rescue !
predicates prodecure check(integer)clauses check(1):-!,write("one"). check(_):-write("something else").goal check(99).
Now check is a procedure. When called it will write one message, and just one !
Slide no: 52
The not PredicateGOAL X=2, not(X>5).
predicates child(symbol) adult(symbol)
clauses child(malte). child(julie).
adult(X):-not(child(X)).
goal% child(leo). % --> No% adult(leo). % --> Yes% adult(julie). % --> No% adult(X). % --> Error: Free variables are not allowed in not
The not predicate is not pure mathematic, it only negates the known facts!
Slide no: 53
Defining lists Lists are writen using square brackets: [ ]
[1,2,3,4] is the list of the numbers from 1 to 4 [lars,ole,finn] is a list of good Danish names [ ] is the empty list.
Visual Prolog programs, requires a definition in the DOMAINS section, descriping the kind of items in list: DOMAINS
slist = STRING* slist is the domain: list of strings clist = CITY* clist is the domain: list of cities
list can be made of any Prolog items, including lists.how is the domain “lists of list of cities”
defined?how does such a list look like?
Slide no: 54
Manipulating lists Lists are processed using a vertical bar “|” The vertical bar divides the list into head
and tail.For example:
[FirstElement | RestOfList ] Unification and| can be used to add an
element to a list: Goal List=[a,b,c], Longerlist = [d|List] Longerlist=[d,a,b,c]
And to take out the first element from a list: Goal List=[a,b,c,d], List=[Head|Tail] Head = a, Tail=[b,c,d]
Slide no: 55
Manipulating Lists
Notice, after the | there may be only a variable. This denotes the rest (i.E. A list). The tail is a list.
Before the | there may be as many objects as we wish to add or to address.
Slide no: 56
Manipulating Lists
Examples: where the list L has the value [a,b,c,d,e,f]:
GOAL l=[a,b,c,d,e,f], l=[head|tail].
Head = a, tail=[b,c,d,e,f].
GOAL l=[a,b,c,d,e,f], L=[X,Y|_].
X=a, y=c.
GOAL l=[a,b,c,d,e,f], l=[_,_|tail].
Tail=[c,d,e,f].
GOAL l=[a,b,c,d,e,f], L=[X,Y,Z]?GOAL l=[a,b,c,d,e,f], L=[_,_,_,_,_,_] ?
Slide no: 57
Generate a list of integer’sDOMAINS List = integer*
predicates genl(integer,list)
clauses genl(0,[]):-!. genl(N,[N|L]):-
N1=N-1,genl(N1,L).
goal genl(10,L).
Slide no: 58
Writing the elements of a list
DOMAINSlist = integer*
PREDICATESwrite_a_list(list)
CLAUSESwrite_a_list([]).
write_a_list([H|T]):-write(“Element: “,H),nl,
write_a_list(T).
GOALwrite_a_list([1, 2, 3]).
Slide no: 59
Counting the elements of a list
DOMAINSlist = integer*PREDICATESlength_of(list,integer)CLAUSESlength_of([], 0).length_of([_|T],L):-
length_of(T,TailLength),L = TailLength + 1.
Slide no: 60
Findall predicateDOMAINS
name,address = stringage = integerlist = age*
PREDICATESnondeterm person(name, address, age)sumlist(list, age, integer Sum)
CLAUSESsumlist([],0,0).sumlist([H|T],Sum,N):-
sumlist(T,S1,N1),Sum=H+S1, N=1+N1.
person("Sherlock Holmes", "22B Baker Street", 42).person("Pete Spiers", "Apt. 22, 21st Street", 36).person("Mary Darrow", "Suite 2, Omega Home", 51).
GOALfindall(Age,person(_, _, Age),L),sumlist(L,Sum,N),Ave = Sum/N,
write("Average=", Ave),nl.
ch0e08.pro
Slide no: 61
Membership of a listDefining member-ships
DOMAINS city=string cities = string*PREDICATES member(city,cities)CLAUSES member(X,[X|_]).
member(X,[_|List]) :- member(X,List)
Exercise
1) add the definition of member to the FLIGHT.PRO program
2) Test the following:to find a member in a list: GOAL L=[a,b,c], member(b,L). GOAL L=[a,b,c], member(d,L).
to get all items in a list try: GOAL member(X,[a,b,c,d]).
3) try to use debugger to see Prolog process the lists.
Slide no: 62
Using lists in FLIGHTS.PRO To avoid loops in the search
performed in the route-predicate, we can consider that we have a list, that is used to contain the cities we have already been in. Thus, each time we try a new city, we should add it to the list:
route(A,B,FTime, ListOfCitiesVisited):- flight(A,New,Time1), ... and then check for membership NewList = [New|ListOfCities], route
Slide no: 63
append
DOMAINSilist = integer*PREDICATESappend(ilist,ilist,ilist)CLAUSESappend([],L,L).append([H|L1],L2,[H|L3]):-
append(L1,L2,L3).
Slide no: 64
Dynamic factsDOMAINS
name, address = stringage = integergender = male ; female
FACTSperson(name, address, age, gender)
PREDICATESmale(name, address, age)female(name, address, age)child(name, age, gender)
CLAUSESmale(Name, Address, Age) :-
person(Name, Address, Age, male).
Slide no: 65
Multiple facts sections
FACTS - mydatabasemyFirstRelation(integer)mySecondRelation(real, string)myThirdRelation(string)/* etc. */
The name is required
The unnamed fact section are called: dbasedom
Every section generates an invisible domain declaration!
Slide no: 66
Determ and single factsfacts
determ daylight_saving(integer)single counter(integer)
clauses counter(0).
Determ: 0 or 1 solutions, never multiple !
single: excactly 1 solution !
Slide no: 67
assertasserta(<the fact>) /* (i) */
asserta(<the fact>, facts_sectionName) /* (i, i) */
assertz(<the fact>) /* (i) */
assertz(<the fact>, facts_sectionName) /* (i, i) */
assert(<the fact>) /* (i) */
assert(<the fact>, facts_sectionName) /* (i, i) */
assertz(person("Suzanne", "New Haven", 35)).asserta(person("Michael", "New York", 26)).assertz(likes("John", "money"), likesDatabase).asserta(likes("Shannon", "hard work"), likesDatabase).
Slide no: 68
retract
retract(<the fact>[, databaseName]) /* (i, i) */
retract(person("Fred", _, _)).retract(likes(_, "broccoli")).retract(likes(_, "money"), likesDatabase).retract(person("Fred", _, _), likesDatabase)
Slide no: 69
retractall
retractall(<the fact>[, databaseName])
Works like defined by:retractall(X):- retract(X), fail.retractall(_).
Retractall will always succeed !
Examples:
retractall(person(_, _, _, male)).retractall(_, mydatabase).
Slide no: 70
consultconsult(fileName) /* (i) */consult(fileName, databaseName) /* (i, i) */
Slide no: 71
save
save(fileName) /* (i) */save(fileName, databaseName) /* (i, i) */
Slide no: 72
Facts handlingassert, retract, save, consult
Visual Prolog support different strategies for databases:(1) internal Prolog fact databases.(2) external Prolog databases (with
extensive support for b+trees etc)(3) external third party databases.
(Bindings is supplied) Method (1) is very easy and work fast
for dataset up to a few thousand records.
Slide no: 73
Arithmetic
A = 1 + 6 / (11 + 3) * Z
Leading "0x" or "0o" signify hexadecimal and octal numbers, respectively, e.g.
0xFFF = 409586 = 0o112 + 12
Slide no: 74
ArithmeticOperand 1 Operator Operand 2 Result
int egral +, -, * int egral int egral
real +, -, * int egral real
int egral +, -, * real real
real +, -, * real real
int egral or real / int egral or real real
int egral div int egral int egral
int egral mod int egral int egral
Slide no: 75
Arithmetic functionsX mod Y, X div Y, abs(X), cos(X),sin(X), tan(X), arctan(X), exp(X),ln(X), log(X), sqrt(X), random(X),random(X, Y), round(X), trunc(X)
Slide no: 76
Free and boundPREDICATES
nondeterm plus(integer, integer, integer)nondeterm num(integer)
CLAUSESplus(X,Y,Z):-
bound(X),bound(Y),Z=X+Y. /* (i,i,o) */plus(X,Y,Z):-
bound(Y),bound(Z),X=Z-Y. /* (o,i,i) */plus(X,Y,Z):-
bound(X),bound(Z),Y=Z-X. /* (i,o,i) */plus(X,Y,Z):-
free(X),free(Y),bound(Z),num(X),Y=Z-X. /* (o,o,i) */plus(X,Y,Z):-
free(X),free(Z),bound(Y),num(X),Z=X+Y. /* (o,i,o) */plus(X,Y,Z):-
free(Y),free(Z),bound(X),num(Y),Z=X+Y. /* (i,o,o) */plus(X,Y,Z):-
free(X),free(Y),free(Z),num(X),num(Y),Z=X+Y. /* (o,o,o) */
num(0).num(X):-
num(A),X = A+1.
Slide no: 77
Declaring a function
PREDICATESunsigned triple(unsigned)
CLAUSEStriple(N,Tpl):- Tpl = N*3.GOAL
TVal = triple(6), write(TVal).
Slide no: 78
Errors and Exception Handling
Invoking an errorexit()exit(ExitCode)errorexit()errorexit(ExitCode)
Catching error’strap(PredicateCall, ExitCode, PredicateToCallOnError)
example:
trap(file_str(“dd.dat”,TextFile),Err,handleErr(“dd.dar”,Err))
errorlevel setting in Compiler
lasterror(ErrNo,Module,IncFile,Pos)
Slide no: 79
String-Handling
concat(String1, String2, String3)format(OutputVariable, FormatString, Variable|Constant*)frontchar(String, FrontChar, RestString)frontstr(UNSIGNED Length, Inpstring, StartString, RestString)fronttoken(String, Token, RestString)isname(StringParam)searchchar(String, Char, UNSIGNED FoundPos)searchstring(String, SearchStr, UNSIGNED FoundPos)str_len(String, UNSIGNED Length)subchar(String, UNSIGNED CharNo, Char)substring(String, UNSIGNED First, UNSIGNED Nbytes, SubString)
Slide no: 80
Writing, Reading, and Fileswrite(Param1, Param2, Param3, ..., ParamN)
readln(Line)
readchar(CharParam)
file_str(Filename, Text) - file_str("t.dat", My_text)
openread(SymbolicFileName, OSFileName)
openwrite(SymbolicFileName, OSFileName)
closefile(SymbolicFileName)
Slide no: 81
Writef and formatwritef(FormatString, Arg1, Arg2, Arg3, ...,ArgN)
writef("A = '%-7' \nB = '%8.1e'\n",A,B),writef("A = '%' \nB = '%8.4e'\n",A,B),nl,writef("C = '%-7.7g' \nD = '%7.7'\n",C,D),writef("C = '%-7.0f' \nD = '%0'\n",C,D),writef("char: %c, decimal: %d, octal: %o, hex: %x",'a','a','a','a').
format(Result,FormatString, Arg1, Arg2, Arg3, ...,ArgN)
Slide no: 82
Password generation ProgramGenerating passwords on the form:Yes58qosKyh12Ciflub58hanfyq28xeqxig64cevvix85Cybpuh84tikVon42RonDes21mofMyv48Qes
Slide no: 83
Password generation Program
predicates genpw(STRING)clauses genpw(PW):-
Vowels = "aeiouy",Consonants = "bcdfghjklmnpqrstvx",Digits = "0123456789",ranchar(Consonants,TC1), ranupper(TC1,C1),ranchar(Vowels,C2),ranchar(Consonants,C3),ranchar(Digits,C4),ranchar(Digits,C5),ranchar(Consonants,TC6), ranupper(TC6,C6),ranchar(Vowels,C7),ranchar(Consonants,C8),
format(PW,"%c%c%c%c%c%c%c%c",C1,C2,C3,C4,C5,C6,C7,C8).
Slide no: 84
Help Predicates
predicates ranchar(string,char)clauses ranchar(S,Char):-
str_len(S,N),random(N,RanNo),Index = RanNo+1,subchar(S,Index,Char).
predicates ranupper(char,char)clauses ranupper(CH,CH):-
random(2,X),X=0,!. ranupper(CH,UpperCH):-
upper_lower(UpperCh,CH).
Slide no: 85
External Databaseterm
term
term
term
term
term
term
term
term
Chain
Chain
Chain
1
2
N
:
:
:
B+Tree
B+Tree
B+Tree
1
2
.
.
.
N
Slide no: 86
System level programmingsystem("ren newcopy.fil newcopy.txt").
envsymbol("SYSDIR", SysDir),
time(Hours, Minutes, Seconds, Hundredths)
date(Year, Month, Day)
comline(CommandLine)
syspath(HomeDir,ExeName)
sleep(CSecs)
sound(Duration,Frequency)
beep()
diskspace(Where,Space)
Slide no: 87
Type CastingResult = cast(returndomain,Expr)
LongVal = cast(LONG,”This was a text”)
Slide no: 88
Predicates as argumentsDeclare a predicate domainDOMAINS
list_process = procedure integer (integer) - (i)
Declare the predicate
PREDICATES square: list_process
Define the clause’s
CLAUSES square(E,ES):- ES = E*E.
Slide no: 89
Exercise RUTES.PRODOMAINS city = STRING ftime = REALPREDICATES flight(city,city, ftime) route(city,city,ftime)CLAUSES flight( mci, stl, 1.0 ). flight( stl, jfk, 2.0 ). flight( stl, lgw, 8.0 ). flight( lgw, cph, 2.0 ). flight( jfk, cdg, 7.0 ).
route(A,B,Ftime):-flight(A,B,Ftime).
route(A,B,Ftime):-flight(A,X,FT1),route(X,B,FT2),Ftime = FT1 + FT2.
Excercise:
1) add the declaration of route to the PREDICATES section of your FLIGHTS.PRO program.
2) add the clauses to the Clauses section
3) Test it with: 3a) GOAL route(mci,cph,X) 3b) GOAL route(cph,mci,X)
4) Obviously, flights have a direction. Experiment how you can get the route concept to utilise flights in both directions
Slide no: 90
Read, write and and string manipulation
Reading readln(X) read a string until terminated
by <CR> readchar(X)read a single charecter when
pressed writing
write(X,Y,”abc”) writes the content of variable X followed by
variable Y followed by the characters “abc”
writef(<formatstring>,variables) gives formatted output
String manipulation fronttoken(String,Token,Rest)
Slide no: 91
Calculator excerciseStarting with +, -, and Integers
DOMAINS tok = plustok;
minustok;numb(INTEGER)
CLAUSES scanning(X,[Token|List]):-
fronttoken(X,Tok,Rest),maketok(Tok,Token),!,
scanning(Rest,List).scanning(_,[]).makeTok(“+”, plustok).makeTok(“-”,minustok).makeTok(X,numb(N)):-
str_int(X,N).
The core of a scanner: The core of a parser
DOMAINS EXP = plus(EXP,EXP);
minus(EXP,EXP);numb(INTEGER)
CLAUSES parse(TokList, RestToks, plus(E1,E2),):-
parse(TokList,Rest1,E1),Rest1 = [plustok|Rest2],parse(Rest2,RestToks,E2).
parse(TokList, RestToks, minus(E1,E2),):-
parse(TokList,Rest1,E1),Rest1 = [minustok|Rest2],parse(Rest2,RestToks,E2).
parse(TokList, RestToks,numb(N) ):-Rest1 = [numb(N)|RestToks].
Slide no: 92
Calculator excercise
DOMAINS EXP = plus(EXP,EXP);
minustok(EXP,EXP);numb(INTEGER)
CLAUSES eval_EXP(plus(E1,E2),V):-
eval_exp(E1,V2),eval_exp(E2,V2),V=V1+V2.
eval_exp(numb(N),N).eval_exp(minus(E1,E2),V):
-eval_exp(E1,V2),eval_exp(E2,V2),V=V1-V2.
The core of the evaluator
GOAL:write(“write an expression:”),readln(Line),scanning(Line,Toklist),parse(Toklist,_,Expression),eval_exp(Expression,Value),nl,nl,write(“The result is: “, Value),readchar(_).
Structure of the calculator
Slide no: 93
The Constants Section
<Id> = <definition>
CONSTANTSblue = 1green = 2red = 4grayfill = [0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 ]language = englishproject_module = true
Slide no: 94
Conditional CompilationCONSTANTS
restricted = 1
ifdef restricted
savebase(_):-write("\nBase cannot be saved in demo version"),readchar(_).
elsedef
savebase(Name):-write("\nSaving ",Name),save(Name).
enddef
Slide no: 95
Memory Management
Stack: the stack is used for transferring arguments and return addresses for predicate calls. The stack also holds the information for backtrackpoints.
Heap: the heap holds all objects that are more or less permanent, such as database facts, window buffers, file buffers etc.
Gstack: the global stack, normally called gstack, is the place where lists, compound structures and strings are placed. The Gstack is only released during backtracking.
Trail: the trail is only used when the program uses reference variables. It holds information about which reference variables must be unbound during backtracking. The trail is allocated in the heap.
Slide no: 96
Splitting a program into modules
You can write, edit, and compile the modules separately, and then link them together to create a single executable program.
Advantages of modular programming:
• A change in code result in compilation of only one module.
• Encapsulation: All predicates local to a module can not be seen from the other modules.
• Natural way to use tools.
• Way to split between multiple programmers.
Slide no: 97
Splitting a program into modules
Slide no: 98
Exported predicates
GLOBAL DOMAINS MYLIST = integer*
GLOBAL PREDICATES project_ShowHelpContext(INTEGER Index) - (i) dlg_about_dialog_Create(WINDOW Parent) - (i) tb_project_toolbar_Create(WINDOW Parent) - (i) tb_help_line_Create(WINDOW Parent) - (i) dlg_kat_Create(WINDOW Parent) - (i)
Slide no: 99
Rules for modular prog.
ALL GLOBAL DOMAINS MUST BE EXACTLY THE SAME IN ALL MODULES. (SAME HEADERFILE INCLUDED).
GLOBAL Predicate definitions can be included in the modules needed !
Slide no: 100
Domain implementationDomain Implementation
16-bit OS 32-bit OS
char, byte 1 byte (see note) 1 byte (see note)
(u)short, word 2 bytes 2 bytes
(u)long, dword 4 bytes 4 bytes
unsigned, integer 2 bytes 4 bytes
real 8 bytes (IEEE format) 8 bytes (IEEE format)
ref 4 bytes 4 bytes
Slide no: 101
Interfacing to other languages
GLOBAL PREDICATESadd(integer,integer,integer) -
(i,i,o),(i,i,i) language cscanner(string,token) - (i,o) language pascaltriple(integer,real) - (i,o) language asm