SlideShare a Scribd company logo
Prolog Built-in predicates

       Dr. M. A. Pasha
Utility goals
• help(S)
  S should be a symbolic atom, e.g.,
  help(assert).
• halt
  Stops Prolog, resume operating system.
• trace, notrace
  Turns trace on and off, respectively.
Universals
• true
  Always succeeds as a goal.
• fail
  Always fails as a goal.
Loading Prolog programs
• consult(F)
  Loads program from the file F. F should be bound to file
  designator expression, e.g.,
  F='/home/user/prolog/sample.pl', depending on the
  file system.
• reconsult(F)
  Like consult except that each predicate already defined
  has its definition replaced by the new definition being
  loaded.
• [F1,F2,...]
  Bracket notation, meaning consult F1, then consult F2,
  then ...
Testing types
• var(Term) succeeds if Term is currently uninstantiated (which therefore
  has not been bound to anything, except possibly another uninstantiated
  variable).
• nonvar(Term) succeeds if Term is currently instantiated (opposite of
  var/1).
• atom(Term) succeeds if Term is currently instantiated to an atom.
• integer(Term) succeeds if Term is currently instantiated to an integer.
• float(Term) succeeds if Term is currently instantiated to a floating point
  number.
• number(Term) succeeds if Term is currently instantiated to an integer or a
  floating point number.

• atomic(Term) succeeds if Term is currently instantiated to an atom, an
  integer or a floating point number.
• string(Term) Tests whether Term is bound to a string.
Arithmetic Predicates
• X is E Evaluate E and unify the result with X.
• X + Y When evaluated, yields the sum of X and Y.
• X - Y When evaluated, yields the difference of X and Y.
• X * Y When evaluated, yields the product of X and Y.
• X / Y When evaluated, yields the quotient of X and Y.
• X mod Y When evaluated, yields the remainder of X
  divided by Y.
• X =:= Y Evaluate X and Y and compare them for
  equality.
• X == Y Evaluate X and Y and succeed if they are not
  equal. ...and similarly for >, <, >=, =<.
?- X=2,Y=3,Z is X+Y.
X = 2,
Y = 3,
Z = 5.

?- X=3, Y=5, X =:= Y .
False

?- X=3, Y=5, X >= Y.
false.

X=3, Y=5, X =< Y.
X = 3,
Y = 5.
Equality of Prolog expressions
• X = Y, X =Y
  Tests whether X and Y can be unified, or cannot,
  respectively. For example, ?- [X,Y|R] = [a,b,c].
  X = a, Y = b, R = [c]
  ?- [X,Y,Z] = [a,b].
  No
• X ==Y, X == Y
  Tests whether X and Y are currently co-bound, i.e.,
  have been bound to or share same value, or not,
  respectively. For example, ?- X = 3, Y = 1 * 3, X == Y.
  no
  ?- X = a, [Y|_]= [a,b,c], X == Y.
  X = a, Y = a
Testing for variables
• ground(G)
  Tests whether G has unbound logical
  variables.
• var(X)
  Tests whether X is bound to a Prolog variable.
Database Manipulation P
• assert(X) Add X to the database. For syntactic reasons, if X
  is not a base clause, use assert((X)).
• asserta(X) Add X to the database in front of other clauses
  of this predicate.
• assertz(X) Add X to the database after other clauses of this
  predicate.
• retract(X) Remove X from the database. For syntactic
  reasons, if X is not a base clause, use retract((X)).
• abolish(F,A) Remove all clauses with functor F and arity A
  from the database.
• clause(X,V) Find a clause in the database whose head (left
  hand side) matches X and whose body (right hand side)
  matches V. To find a base clause, use true for V.
Assert and Retract
• asserta(C)
  Assert clause C into database above other clauses with
  the same key predicate. The key predicate of a clause is
  the first predicate encountered when the clause is read
  from left to right.
• assertz(C), assert(C)
  Assert clause C into database below other clauses with
  the same key predicate.
• retract(C)
  Retract C from the database. C must be sufficiently
  instantiated to determine the predicate key.
Binding a logical variable to a numeric
                 value
• X is E
  Binds logical variable V to the numerical value of
  E. The expression E must either be a number or
  be a number-valued expression, conventionally
  parenthesized,
• ?- X is 22, Y is X * 3, Z is sqrt(Y).
  X = 22 .
  Y = 66 .
  Z = 8.12404 .
• ?- X is sin(45).
  X = 0.8509035245341184.
Control Predicates
• X ; Y X or Y. Try X first; if it fails (possibly after being backtracked
  into), try Y.
• (X -> Y) If X, then try Y, otherwise fail. Y will not be backtracked into.
• (X -> Y ; Z) If X, then try Y, else try Z. X will not be backtracked into.
• not X (Sometimes written +X or not(X)) Succeed only when X fails.
• true Succeed once, but fail when backtracked into.
• repeat Always succeed, even when backtracked into.
• fail Never succeed.
• ! (Pronounced ``cut".) Acts like true, but cannot be backtracked
  past, and prevents any other clauses of the predicate it occurs in
  from being tried.
• abort Return immediately to the top-level Prolog prompt.
Negation as failure
• not(Q), +Q
  Negation-as-failure, as if defined by:
• not(Q) :- call(Q), !, fail.
  not(Q).
Prolog terms and clauses as data
• name(A,L)
  Convert between atom and list.
• ?- name('pasha', P).
  P = [112, 97, 115, 104, 97].

• ?- parent(a,X) = .. L.
  L = [parent, a, _X001]

• ?- P=..[parent,pasha, abdul].
  P= parent(pasha,abdul)
Associativity
• associativity (or fixity) of an operator is a
  property that determines how operators of
  the same precedence are grouped in the
  absence of parentheses.
• Operators may be left-associative (meaning
  the operations are grouped from the left),
  right-associative (meaning the operations are
  grouped from the right) or non-associative
  (meaning there is no defined grouping).
Prolog operators
Operator Type
• xfx infix nonassociative
  xfy infix right-associative
  yfx infix left-associative
  fx prefix nonassociative
  fy prefix right-associative
  xf postfix nonassociative
  yf postfix left-associative
Prolog operators
•   :-              xfx, fx
•   ?-              fx
•   ;               xfy
•   ,               xfy
•   not             fy
•   is, =.. , <     xfx
•   +, -            yfx, fx
•   *, /            yfx
•   ^               xfy
• :- op(P,T,O).
  Declare an operator symbol. For example, with source
  program ...
• :- op(500,xfx,'has_color').
  a has_color red.
  b has_color blue.Then ...
• ?- b has_color C.
  C = red
  ?- What has_color red.
  What = aP is precedence, an integer. Larger P has less
  precedence (ability to group). Precedence number values
  for built-ins depend upon the actual Prolog system. User
  needs to find out what these values are. (See the reference
  materials or use the help facility with keyword 'operator').
Finding all answers
• findall(Things,GoalExpression,Bag)
  Compute all Things which satisfy the GoalExpresssion and
  collect them in the list Bag. If the GoalExpression fails, Bag
  will be the empty list []. findall treats all variables in
  GoalExpression as if they are existentially quantified.
• bagof(Things,GoalExpression,Bag)
  Compute all Things which satisfy the GoalExpresssion and
  collect them in the list Bag. bagof fails if GoalExpression
  fails. Free variables in GoalExpression could be
  bound, yielding many bags.
• setof(Things,GoalExpression,Bag)
  Compute all Things which satisfy the GoalExpresssion and
  collect them in the list Bag. Similar to bagof except that Bag
  will not contain duplicates and it will be sorted.
Example
son(X,Y):-                 ?- findall(X, father(X,Y), Bag).
     father(Y,X),
     male(X).              Bag = [afzal, afzal, nazir,
daughter(X, Y):-              afzal, afzal].
    father(Y, X),
    female(X).

grandfather(X, Y):-
     father(X, Z),
                           ?- findall(Y, father(X,Y), Bag).
     father(Z,Y).
                           Bag = [bilal, zubair, afzal,
father(afzal, bilal).
father(afzal, zubair).        humara, sumara].
father(nazir, afzal).
father(afzal, humara).
father(afzal, sumara).

female(sumara).
female(humara).
p(1,3,5).
   p(2,4,1).
   p(3,5,2).
   p(4,3,1).
   p(5,2,4).
?- bagof(Z,p(X,Y,Z),Bag).
X = 1, Y = 3, Bag = [5] ;     The predicates bagof and setof yield
X = 2,Y = 4,Bag = [1] ;       collections for individual bindings of the
X = 3,Y = 5,Bag = [2] ;       free variables in the goal.
X = 4,Y = 3,Bag = [1] ;       setof yields a sorted version of the
X = 5,Y = 2,Bag = [4].        collection without duplicates.

?- findall(Z,p(X,Y,Z),Bag).
Bag = [5, 1, 2, 1, 4].
Output Predicates
• write(X) Write the single value X to the current
  output file.
• writeq(X) Write X with quotes as needed so it can
  be read in again.
• tab(N) Write N blanks to the current output file.
• nl Write a newline to the current output file.
• put(X) Write the character whose ASCII value is X
  to the current output file.
• tell(File) Open File as the current output file.
• told Close the current output file.
Input predicates
• read(X) Read one clause from the current input
  and unify it with X. If there is no further input, X
  is unified with end_of_file.
• get(X) Read one printing character from the
  current input file and unify the ASCII code of that
  character (an integer) with X.
• get0(X) Read one character from the current
  input file and unify the ASCII code of that
  character with X.
• see(File) Open File as the current input file.
• seen Close the current input file.
To avoid binding variables, use an existential quantifier
 expression. For example the goal bagof(Z,X^Y^p(X,Y,Z),Bag) asks
 for "the Bag of Z's such that there exists an X and there exists a Y
 such that p(X,Y,Z)".

           ?-setof(Z,X^Y^p(X,Y,Z),Bag).
           Bag = [1, 2, 4, 5].

findall acts like bagof with all free variables automatically
existentially quantified. In addition findall returns an empty list []
there is no goal satisfaction, whereas bagof fails.

         ?- bagof(Z,(p(X,Y,Z),Z>5),Bag).
         False.
         ?- findall(Z,(p(X,Y,Z),Z>5),Bag).
         Bag = []
Listing and Debugging Predicates
•   listing(P)
    Display predicate P. P may be a predicate name, a structure of the form
    Name/Arity, or a bracked list of the above.
•   trace
    Turn on tracing.
•   notrace
    Turn off tracing.
•   spy P
    Turn on tracing when predicate P is called. P may be a predicate name, a structure
    of the form Name/Arity, or a non-bracked list of the above.
•   nospy P
    Turn off spying for P.
•   nospyall
    Turn off all spypoints.
•   Debug
     Enable spypoints (allow them to initiate tracing.).
•   Nodebug
    Disable spypoints (without removing them).

More Related Content

PDF
Ejercicios de estilo en la programación
Software Guru
 
PDF
20170509 rand db_lesugent
Prof. Wim Van Criekinge
 
PDF
Expressiveness and Model of the Polymorphic λ Calculus
evastsdsh
 
PPTX
P3 2017 python_regexes
Prof. Wim Van Criekinge
 
PPT
09 logic programming
saru40
 
PDF
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Franklin Chen
 
PDF
Data Structures In Scala
Knoldus Inc.
 
PPTX
Proposals for new function in Java SE 9 and beyond
Barry Feigenbaum
 
Ejercicios de estilo en la programación
Software Guru
 
20170509 rand db_lesugent
Prof. Wim Van Criekinge
 
Expressiveness and Model of the Polymorphic λ Calculus
evastsdsh
 
P3 2017 python_regexes
Prof. Wim Van Criekinge
 
09 logic programming
saru40
 
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Franklin Chen
 
Data Structures In Scala
Knoldus Inc.
 
Proposals for new function in Java SE 9 and beyond
Barry Feigenbaum
 

What's hot (17)

PDF
Python data handling notes
Prof. Dr. K. Adisesha
 
ODP
Type Parameterization
Knoldus Inc.
 
ODP
Functions In Scala
Knoldus Inc.
 
ODP
Effective way to code in Scala
Knoldus Inc.
 
PPT
Prolog programming
Harry Potter
 
PPT
Pl vol1
Aarsh Ps
 
PDF
[FLOLAC'14][scm] Functional Programming Using Haskell
Functional Thursday
 
PDF
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
PDF
Functional Programming by Examples using Haskell
goncharenko
 
PDF
Python list
Prof. Dr. K. Adisesha
 
PDF
Frp2016 3
Kirill Kozlov
 
PDF
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
PPTX
PROLOG: Cuts And Negation In Prolog
DataminingTools Inc
 
PPTX
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
PDF
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
ODP
Introduction To Regex in Lasso 8.5
bilcorry
 
KEY
0211 ch 2 day 11
festivalelmo
 
Python data handling notes
Prof. Dr. K. Adisesha
 
Type Parameterization
Knoldus Inc.
 
Functions In Scala
Knoldus Inc.
 
Effective way to code in Scala
Knoldus Inc.
 
Prolog programming
Harry Potter
 
Pl vol1
Aarsh Ps
 
[FLOLAC'14][scm] Functional Programming Using Haskell
Functional Thursday
 
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
Functional Programming by Examples using Haskell
goncharenko
 
Frp2016 3
Kirill Kozlov
 
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
PROLOG: Cuts And Negation In Prolog
DataminingTools Inc
 
Purely Functional Data Structures in Scala
Vladimir Kostyukov
 
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
Introduction To Regex in Lasso 8.5
bilcorry
 
0211 ch 2 day 11
festivalelmo
 
Ad

Viewers also liked (16)

PPT
Aula Prolog 09 - Listas
Fabio Moura Pereira
 
PPTX
Regression and Classification: An Artificial Neural Network Approach
Khulna University
 
PPTX
Lecture 25 hill climbing
Hema Kashyap
 
PPT
Neural network
EasyMedico.com
 
PPT
Artificial Intelligence AI Topics History and Overview
butest
 
PPTX
Introduction to Neural networks (under graduate course) Lecture 3 of 9
Randa Elanwar
 
PPTX
Lecture 14 Heuristic Search-A star algorithm
Hema Kashyap
 
PPT
Artificial intelligence
iarthur
 
PPTX
Hill-climbing #2
Mohamed Gad
 
PPTX
hopfield neural network
Abhishikha Sinha
 
ODP
Hillclimbing search algorthim #introduction
Mohamed Gad
 
PPTX
HOPFIELD NETWORK
ankita pandey
 
PPTX
Introduction to Prolog
Chamath Sajeewa
 
PPT
Hill climbing
Mohammad Faizan
 
PPTX
Artificial Intelligence Presentation
lpaviglianiti
 
PPT
Artificial Intelligence
u053675
 
Aula Prolog 09 - Listas
Fabio Moura Pereira
 
Regression and Classification: An Artificial Neural Network Approach
Khulna University
 
Lecture 25 hill climbing
Hema Kashyap
 
Neural network
EasyMedico.com
 
Artificial Intelligence AI Topics History and Overview
butest
 
Introduction to Neural networks (under graduate course) Lecture 3 of 9
Randa Elanwar
 
Lecture 14 Heuristic Search-A star algorithm
Hema Kashyap
 
Artificial intelligence
iarthur
 
Hill-climbing #2
Mohamed Gad
 
hopfield neural network
Abhishikha Sinha
 
Hillclimbing search algorthim #introduction
Mohamed Gad
 
HOPFIELD NETWORK
ankita pandey
 
Introduction to Prolog
Chamath Sajeewa
 
Hill climbing
Mohammad Faizan
 
Artificial Intelligence Presentation
lpaviglianiti
 
Artificial Intelligence
u053675
 
Ad

Similar to Prolog2 (1) (20)

PPTX
Prolog 7-Languages
Pierre de Lacaze
 
PDF
Logic Programming and ILP
Pierre de Lacaze
 
PPT
Chaps 1-3-ai-prolog
juanpaperez1234
 
PPT
Prolog 01
saru40
 
DOCX
AI Lab Manual.docx
KPRevathiAsstprofITD
 
PPT
Prolog basics
shivani saluja
 
PPT
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
Kdas004
 
PPTX
Prolog & lisp
Ismail El Gayar
 
PDF
"That scripting language called Prolog"
Sergei Winitzki
 
PPTX
PROLOG: Introduction To Prolog
DataminingTools Inc
 
DOCX
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
monicafrancis71118
 
PPT
Chaps 1-3-ai-prolog
saru40
 
PPTX
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
qasim ali
 
DOCX
Prolog_Programminvfygugy7gtugbugtg_Notes.docx
ap04944
 
PPTX
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
ManishYadav243888
 
PDF
Ai lab manual
Shipra Swati
 
DOCX
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
cargillfilberto
 
DOCX
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
drandy1
 
PDF
10 logic+programming+with+prolog
baran19901990
 
PPT
Prolog programming
Young Alista
 
Prolog 7-Languages
Pierre de Lacaze
 
Logic Programming and ILP
Pierre de Lacaze
 
Chaps 1-3-ai-prolog
juanpaperez1234
 
Prolog 01
saru40
 
AI Lab Manual.docx
KPRevathiAsstprofITD
 
Prolog basics
shivani saluja
 
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
Kdas004
 
Prolog & lisp
Ismail El Gayar
 
"That scripting language called Prolog"
Sergei Winitzki
 
PROLOG: Introduction To Prolog
DataminingTools Inc
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
monicafrancis71118
 
Chaps 1-3-ai-prolog
saru40
 
UOS-BSIT-3811-Artificial-Intelligence-Introduction-to-prolog-PDF.pptx
qasim ali
 
Prolog_Programminvfygugy7gtugbugtg_Notes.docx
ap04944
 
Unit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit 3 Prolog.pptxUnit
ManishYadav243888
 
Ai lab manual
Shipra Swati
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
cargillfilberto
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
drandy1
 
10 logic+programming+with+prolog
baran19901990
 
Prolog programming
Young Alista
 

More from university of sargodha (10)

PPT
Soft computing06
university of sargodha
 
PPTX
Soft computing01
university of sargodha
 
DOCX
Final taxo
university of sargodha
 
PPTX
Advance analysis of algo
university of sargodha
 
PPTX
Soft computing08
university of sargodha
 
PPTX
Presentation1
university of sargodha
 
PPTX
Lecture 32 fuzzy systems
university of sargodha
 
PPTX
Lecture 29 fuzzy systems
university of sargodha
 
PPT
Cobi t riskmanagementframework_iac
university of sargodha
 
PPTX
Soft computing09
university of sargodha
 
Soft computing06
university of sargodha
 
Soft computing01
university of sargodha
 
Advance analysis of algo
university of sargodha
 
Soft computing08
university of sargodha
 
Presentation1
university of sargodha
 
Lecture 32 fuzzy systems
university of sargodha
 
Lecture 29 fuzzy systems
university of sargodha
 
Cobi t riskmanagementframework_iac
university of sargodha
 
Soft computing09
university of sargodha
 

Prolog2 (1)

  • 1. Prolog Built-in predicates Dr. M. A. Pasha
  • 2. Utility goals • help(S) S should be a symbolic atom, e.g., help(assert). • halt Stops Prolog, resume operating system. • trace, notrace Turns trace on and off, respectively.
  • 3. Universals • true Always succeeds as a goal. • fail Always fails as a goal.
  • 4. Loading Prolog programs • consult(F) Loads program from the file F. F should be bound to file designator expression, e.g., F='/home/user/prolog/sample.pl', depending on the file system. • reconsult(F) Like consult except that each predicate already defined has its definition replaced by the new definition being loaded. • [F1,F2,...] Bracket notation, meaning consult F1, then consult F2, then ...
  • 5. Testing types • var(Term) succeeds if Term is currently uninstantiated (which therefore has not been bound to anything, except possibly another uninstantiated variable). • nonvar(Term) succeeds if Term is currently instantiated (opposite of var/1). • atom(Term) succeeds if Term is currently instantiated to an atom. • integer(Term) succeeds if Term is currently instantiated to an integer. • float(Term) succeeds if Term is currently instantiated to a floating point number. • number(Term) succeeds if Term is currently instantiated to an integer or a floating point number. • atomic(Term) succeeds if Term is currently instantiated to an atom, an integer or a floating point number. • string(Term) Tests whether Term is bound to a string.
  • 6. Arithmetic Predicates • X is E Evaluate E and unify the result with X. • X + Y When evaluated, yields the sum of X and Y. • X - Y When evaluated, yields the difference of X and Y. • X * Y When evaluated, yields the product of X and Y. • X / Y When evaluated, yields the quotient of X and Y. • X mod Y When evaluated, yields the remainder of X divided by Y. • X =:= Y Evaluate X and Y and compare them for equality. • X == Y Evaluate X and Y and succeed if they are not equal. ...and similarly for >, <, >=, =<.
  • 7. ?- X=2,Y=3,Z is X+Y. X = 2, Y = 3, Z = 5. ?- X=3, Y=5, X =:= Y . False ?- X=3, Y=5, X >= Y. false. X=3, Y=5, X =< Y. X = 3, Y = 5.
  • 8. Equality of Prolog expressions • X = Y, X =Y Tests whether X and Y can be unified, or cannot, respectively. For example, ?- [X,Y|R] = [a,b,c]. X = a, Y = b, R = [c] ?- [X,Y,Z] = [a,b]. No • X ==Y, X == Y Tests whether X and Y are currently co-bound, i.e., have been bound to or share same value, or not, respectively. For example, ?- X = 3, Y = 1 * 3, X == Y. no ?- X = a, [Y|_]= [a,b,c], X == Y. X = a, Y = a
  • 9. Testing for variables • ground(G) Tests whether G has unbound logical variables. • var(X) Tests whether X is bound to a Prolog variable.
  • 10. Database Manipulation P • assert(X) Add X to the database. For syntactic reasons, if X is not a base clause, use assert((X)). • asserta(X) Add X to the database in front of other clauses of this predicate. • assertz(X) Add X to the database after other clauses of this predicate. • retract(X) Remove X from the database. For syntactic reasons, if X is not a base clause, use retract((X)). • abolish(F,A) Remove all clauses with functor F and arity A from the database. • clause(X,V) Find a clause in the database whose head (left hand side) matches X and whose body (right hand side) matches V. To find a base clause, use true for V.
  • 11. Assert and Retract • asserta(C) Assert clause C into database above other clauses with the same key predicate. The key predicate of a clause is the first predicate encountered when the clause is read from left to right. • assertz(C), assert(C) Assert clause C into database below other clauses with the same key predicate. • retract(C) Retract C from the database. C must be sufficiently instantiated to determine the predicate key.
  • 12. Binding a logical variable to a numeric value • X is E Binds logical variable V to the numerical value of E. The expression E must either be a number or be a number-valued expression, conventionally parenthesized, • ?- X is 22, Y is X * 3, Z is sqrt(Y). X = 22 . Y = 66 . Z = 8.12404 . • ?- X is sin(45). X = 0.8509035245341184.
  • 13. Control Predicates • X ; Y X or Y. Try X first; if it fails (possibly after being backtracked into), try Y. • (X -> Y) If X, then try Y, otherwise fail. Y will not be backtracked into. • (X -> Y ; Z) If X, then try Y, else try Z. X will not be backtracked into. • not X (Sometimes written +X or not(X)) Succeed only when X fails. • true Succeed once, but fail when backtracked into. • repeat Always succeed, even when backtracked into. • fail Never succeed. • ! (Pronounced ``cut".) Acts like true, but cannot be backtracked past, and prevents any other clauses of the predicate it occurs in from being tried. • abort Return immediately to the top-level Prolog prompt.
  • 14. Negation as failure • not(Q), +Q Negation-as-failure, as if defined by: • not(Q) :- call(Q), !, fail. not(Q).
  • 15. Prolog terms and clauses as data • name(A,L) Convert between atom and list. • ?- name('pasha', P). P = [112, 97, 115, 104, 97]. • ?- parent(a,X) = .. L. L = [parent, a, _X001] • ?- P=..[parent,pasha, abdul]. P= parent(pasha,abdul)
  • 16. Associativity • associativity (or fixity) of an operator is a property that determines how operators of the same precedence are grouped in the absence of parentheses. • Operators may be left-associative (meaning the operations are grouped from the left), right-associative (meaning the operations are grouped from the right) or non-associative (meaning there is no defined grouping).
  • 17. Prolog operators Operator Type • xfx infix nonassociative xfy infix right-associative yfx infix left-associative fx prefix nonassociative fy prefix right-associative xf postfix nonassociative yf postfix left-associative
  • 18. Prolog operators • :- xfx, fx • ?- fx • ; xfy • , xfy • not fy • is, =.. , < xfx • +, - yfx, fx • *, / yfx • ^ xfy
  • 19. • :- op(P,T,O). Declare an operator symbol. For example, with source program ... • :- op(500,xfx,'has_color'). a has_color red. b has_color blue.Then ... • ?- b has_color C. C = red ?- What has_color red. What = aP is precedence, an integer. Larger P has less precedence (ability to group). Precedence number values for built-ins depend upon the actual Prolog system. User needs to find out what these values are. (See the reference materials or use the help facility with keyword 'operator').
  • 20. Finding all answers • findall(Things,GoalExpression,Bag) Compute all Things which satisfy the GoalExpresssion and collect them in the list Bag. If the GoalExpression fails, Bag will be the empty list []. findall treats all variables in GoalExpression as if they are existentially quantified. • bagof(Things,GoalExpression,Bag) Compute all Things which satisfy the GoalExpresssion and collect them in the list Bag. bagof fails if GoalExpression fails. Free variables in GoalExpression could be bound, yielding many bags. • setof(Things,GoalExpression,Bag) Compute all Things which satisfy the GoalExpresssion and collect them in the list Bag. Similar to bagof except that Bag will not contain duplicates and it will be sorted.
  • 21. Example son(X,Y):- ?- findall(X, father(X,Y), Bag). father(Y,X), male(X). Bag = [afzal, afzal, nazir, daughter(X, Y):- afzal, afzal]. father(Y, X), female(X). grandfather(X, Y):- father(X, Z), ?- findall(Y, father(X,Y), Bag). father(Z,Y). Bag = [bilal, zubair, afzal, father(afzal, bilal). father(afzal, zubair). humara, sumara]. father(nazir, afzal). father(afzal, humara). father(afzal, sumara). female(sumara). female(humara).
  • 22. p(1,3,5). p(2,4,1). p(3,5,2). p(4,3,1). p(5,2,4). ?- bagof(Z,p(X,Y,Z),Bag). X = 1, Y = 3, Bag = [5] ; The predicates bagof and setof yield X = 2,Y = 4,Bag = [1] ; collections for individual bindings of the X = 3,Y = 5,Bag = [2] ; free variables in the goal. X = 4,Y = 3,Bag = [1] ; setof yields a sorted version of the X = 5,Y = 2,Bag = [4]. collection without duplicates. ?- findall(Z,p(X,Y,Z),Bag). Bag = [5, 1, 2, 1, 4].
  • 23. Output Predicates • write(X) Write the single value X to the current output file. • writeq(X) Write X with quotes as needed so it can be read in again. • tab(N) Write N blanks to the current output file. • nl Write a newline to the current output file. • put(X) Write the character whose ASCII value is X to the current output file. • tell(File) Open File as the current output file. • told Close the current output file.
  • 24. Input predicates • read(X) Read one clause from the current input and unify it with X. If there is no further input, X is unified with end_of_file. • get(X) Read one printing character from the current input file and unify the ASCII code of that character (an integer) with X. • get0(X) Read one character from the current input file and unify the ASCII code of that character with X. • see(File) Open File as the current input file. • seen Close the current input file.
  • 25. To avoid binding variables, use an existential quantifier expression. For example the goal bagof(Z,X^Y^p(X,Y,Z),Bag) asks for "the Bag of Z's such that there exists an X and there exists a Y such that p(X,Y,Z)". ?-setof(Z,X^Y^p(X,Y,Z),Bag). Bag = [1, 2, 4, 5]. findall acts like bagof with all free variables automatically existentially quantified. In addition findall returns an empty list [] there is no goal satisfaction, whereas bagof fails. ?- bagof(Z,(p(X,Y,Z),Z>5),Bag). False. ?- findall(Z,(p(X,Y,Z),Z>5),Bag). Bag = []
  • 26. Listing and Debugging Predicates • listing(P) Display predicate P. P may be a predicate name, a structure of the form Name/Arity, or a bracked list of the above. • trace Turn on tracing. • notrace Turn off tracing. • spy P Turn on tracing when predicate P is called. P may be a predicate name, a structure of the form Name/Arity, or a non-bracked list of the above. • nospy P Turn off spying for P. • nospyall Turn off all spypoints. • Debug Enable spypoints (allow them to initiate tracing.). • Nodebug Disable spypoints (without removing them).

Editor's Notes

  • #2: http://matuszek.org/prolog/prolog-lists.htmlhttp://cs.union.edu/~striegnk/learn-prolog-now/html/node94.html#sec.l11.database.manip