SlideShare ist ein Scribd-Unternehmen logo
1 von 26
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).

Weitere ähnliche Inhalte

Was ist angesagt?

Type Parameterization
Type ParameterizationType Parameterization
Type ParameterizationKnoldus Inc.
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in ScalaKnoldus Inc.
 
Prolog programming
Prolog programmingProlog programming
Prolog programmingHarry Potter
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using HaskellFunctional Thursday
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Chia-Chi Chang
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...gjcross
 
PROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologPROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologDataminingTools Inc
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Introduction To Regex in Lasso 8.5
Introduction To Regex in Lasso 8.5Introduction To Regex in Lasso 8.5
Introduction To Regex in Lasso 8.5bilcorry
 

Was ist angesagt? (17)

Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
 
Pl vol1
Pl vol1Pl vol1
Pl vol1
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Python list
Python listPython list
Python list
 
Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
 
PROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In PrologPROLOG: Cuts And Negation In Prolog
PROLOG: Cuts And Negation In Prolog
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Introduction To Regex in Lasso 8.5
Introduction To Regex in Lasso 8.5Introduction To Regex in Lasso 8.5
Introduction To Regex in Lasso 8.5
 
0211 ch 2 day 11
0211 ch 2 day 110211 ch 2 day 11
0211 ch 2 day 11
 

Andere mochten auch

Regression and Classification: An Artificial Neural Network Approach
Regression and Classification: An Artificial Neural Network ApproachRegression and Classification: An Artificial Neural Network Approach
Regression and Classification: An Artificial Neural Network ApproachKhulna University
 
Lecture 25 hill climbing
Lecture 25 hill climbingLecture 25 hill climbing
Lecture 25 hill climbingHema Kashyap
 
Artificial Intelligence AI Topics History and Overview
Artificial Intelligence AI Topics History and OverviewArtificial Intelligence AI Topics History and Overview
Artificial Intelligence AI Topics History and Overviewbutest
 
Introduction to Neural networks (under graduate course) Lecture 3 of 9
Introduction to Neural networks (under graduate course) Lecture 3 of 9Introduction to Neural networks (under graduate course) Lecture 3 of 9
Introduction to Neural networks (under graduate course) Lecture 3 of 9Randa Elanwar
 
Lecture 14 Heuristic Search-A star algorithm
Lecture 14 Heuristic Search-A star algorithmLecture 14 Heuristic Search-A star algorithm
Lecture 14 Heuristic Search-A star algorithmHema Kashyap
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligenceiarthur
 
Hill-climbing #2
Hill-climbing #2Hill-climbing #2
Hill-climbing #2Mohamed Gad
 
Hillclimbing search algorthim #introduction
Hillclimbing search algorthim #introductionHillclimbing search algorthim #introduction
Hillclimbing search algorthim #introductionMohamed Gad
 
Artificial Intelligence Presentation
Artificial Intelligence PresentationArtificial Intelligence Presentation
Artificial Intelligence Presentationlpaviglianiti
 
Artificial Intelligence
Artificial IntelligenceArtificial Intelligence
Artificial Intelligenceu053675
 

Andere mochten auch (16)

Aula Prolog 09 - Listas
Aula Prolog 09 - ListasAula Prolog 09 - Listas
Aula Prolog 09 - Listas
 
Regression and Classification: An Artificial Neural Network Approach
Regression and Classification: An Artificial Neural Network ApproachRegression and Classification: An Artificial Neural Network Approach
Regression and Classification: An Artificial Neural Network Approach
 
Lecture 25 hill climbing
Lecture 25 hill climbingLecture 25 hill climbing
Lecture 25 hill climbing
 
Neural network
Neural networkNeural network
Neural network
 
Artificial Intelligence AI Topics History and Overview
Artificial Intelligence AI Topics History and OverviewArtificial Intelligence AI Topics History and Overview
Artificial Intelligence AI Topics History and Overview
 
Introduction to Neural networks (under graduate course) Lecture 3 of 9
Introduction to Neural networks (under graduate course) Lecture 3 of 9Introduction to Neural networks (under graduate course) Lecture 3 of 9
Introduction to Neural networks (under graduate course) Lecture 3 of 9
 
Lecture 14 Heuristic Search-A star algorithm
Lecture 14 Heuristic Search-A star algorithmLecture 14 Heuristic Search-A star algorithm
Lecture 14 Heuristic Search-A star algorithm
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligence
 
Hill-climbing #2
Hill-climbing #2Hill-climbing #2
Hill-climbing #2
 
hopfield neural network
hopfield neural networkhopfield neural network
hopfield neural network
 
Hillclimbing search algorthim #introduction
Hillclimbing search algorthim #introductionHillclimbing search algorthim #introduction
Hillclimbing search algorthim #introduction
 
HOPFIELD NETWORK
HOPFIELD NETWORKHOPFIELD NETWORK
HOPFIELD NETWORK
 
Introduction to Prolog
Introduction to PrologIntroduction to Prolog
Introduction to Prolog
 
Hill climbing
Hill climbingHill climbing
Hill climbing
 
Artificial Intelligence Presentation
Artificial Intelligence PresentationArtificial Intelligence Presentation
Artificial Intelligence Presentation
 
Artificial Intelligence
Artificial IntelligenceArtificial Intelligence
Artificial Intelligence
 

Ähnlich wie Prolog2 (1)

Ähnlich wie Prolog2 (1) (20)

Pl vol1
Pl vol1Pl vol1
Pl vol1
 
Functionsandpigeonholeprinciple
FunctionsandpigeonholeprincipleFunctionsandpigeonholeprinciple
Functionsandpigeonholeprinciple
 
Ch01
Ch01Ch01
Ch01
 
Prolog
PrologProlog
Prolog
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
 
Wrong
WrongWrong
Wrong
 
#8 formal methods – pro logic
#8 formal methods – pro logic#8 formal methods – pro logic
#8 formal methods – pro logic
 
Chaps 1-3-ai-prolog
Chaps 1-3-ai-prologChaps 1-3-ai-prolog
Chaps 1-3-ai-prolog
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Prolog basics
Prolog basicsProlog basics
Prolog basics
 
Chaps 1-3-ai-prolog
Chaps 1-3-ai-prologChaps 1-3-ai-prolog
Chaps 1-3-ai-prolog
 
ProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) IntroductionProLog (Artificial Intelligence) Introduction
ProLog (Artificial Intelligence) Introduction
 
Lesson 1: Functions
Lesson 1: FunctionsLesson 1: Functions
Lesson 1: Functions
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Prolog 01
Prolog 01Prolog 01
Prolog 01
 
app4.pptx
app4.pptxapp4.pptx
app4.pptx
 
X02PredCalculus.ppt
X02PredCalculus.pptX02PredCalculus.ppt
X02PredCalculus.ppt
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
 
Erlang
ErlangErlang
Erlang
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 

Mehr von university of sargodha (10)

Soft computing06
Soft computing06Soft computing06
Soft computing06
 
Soft computing01
Soft computing01Soft computing01
Soft computing01
 
Final taxo
Final taxoFinal taxo
Final taxo
 
Advance analysis of algo
Advance analysis of algoAdvance analysis of algo
Advance analysis of algo
 
Soft computing08
Soft computing08Soft computing08
Soft computing08
 
Presentation1
Presentation1Presentation1
Presentation1
 
Lecture 32 fuzzy systems
Lecture 32   fuzzy systemsLecture 32   fuzzy systems
Lecture 32 fuzzy systems
 
Lecture 29 fuzzy systems
Lecture 29   fuzzy systemsLecture 29   fuzzy systems
Lecture 29 fuzzy systems
 
Cobi t riskmanagementframework_iac
Cobi t riskmanagementframework_iacCobi t riskmanagementframework_iac
Cobi t riskmanagementframework_iac
 
Soft computing09
Soft computing09Soft computing09
Soft computing09
 

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).

Hinweis der Redaktion

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