SlideShare a Scribd company logo
Recursion and Lists in Prolog
OVERVIEWRecursive definitionsClause ordering, goal ordering, and termination.ListsMembersRecursing Down Lists
Recursive definitionsA predicate is recursively defined if one or more rules in its definition refers to itself.Ex: is_digesting(X,Y) :- just_ate(X,Y).is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y).just_ate(mosquito,blood(john)).just_ate(frog,mosquito).just_ate(stork,frog). It's just a knowledge base containing two facts andtwo rules. But the definition of the is_digesting/2 predicate is recursive.
Another way of writing numerals, which is sometimes used in mathematical logic is to makes use of just four symbols: 0, succ, and the left and right brackets. This style of numeral is defined by the following inductive definition:1. 0 is a numeral.2. If X is a numeral, then so is succ(X).This definition in prolog program is written as:numeral(0).numeral(succ(X)) :- numeral(X).So, on posing the query numeral(succ(succ(succ(0)))).We get Yes.Now on running the following querynumeral(X).we can have the following dialogue with Prolog:X = 0 ;X = succ(0) ;X = succ(succ(0)) ;X = succ(succ(succ(0))) ;X = succ(succ(succ(succ(0)))) ;X = succ(succ(succ(succ(succ(0))))) ;X = succ(succ(succ(succ(succ(succ(0)))))) ;X = succ(succ(succ(succ(succ(succ(succ(0))))))) ;X = succ(succ(succ(succ(succ(succ(succ(succ(0)))))))) ;X = succ(succ(succ(succ(succ(succ(succ(succ(succ(0))))))))) ;X = succ(succ(succ(succ(succ(succ(succ(succ(succ(succ(0))))))))))YesIt's backtracking through the recursive definition, and actually building numerals using matching.
Clause ordering, goal ordering, and terminationConsider the following ex:child(martha,charlotte).child(charlotte,caroline).child(caroline,laura).child(laura,rose).descend(X,Y) :- child(X,Y).descend(X,Y) :- child(X,Z),descend(Z,Y).We'll make two changes to it, and call the result descend2.pl:child(martha,charlotte).child(charlotte,caroline).child(caroline,laura).child(laura,rose).descend(X,Y) :- descend(Z,Y),child(X,Z).descend(X,Y) :- child(X,Y).
we have merely reversed the order of the two rules, and reversed the order of the two goals in the recursive clause. So, viewed as a purely logical definition, nothing has changed.But the procedural meaning has changed dramatically. For example, if you pose the querydescend(martha,rose).you will get an error message (`out of local stack', or something similar).Because descend1.pl and descend2.pl are Prolog knowledge bases with the same declarative meaning but different procedural meanings: from a purely logical perspective they are identical, but they behave very differently.
The declarative and procedural meanings of a Prolog program can differ, when writing Prolog programs you need to bear both aspects in mind.When you need to think about how Prolog will actually evaluate queries. The following questions must be considered:Are the rule orderings sensible? How will the program actually run?
Listslists, an important recursive data structure widely used in computational linguistics.It is a finite sequence of elements. Here are some examples of lists in Prolog:[mia, vincent, jules, yolanda][mia, robber(honey_bunny), X, 2, mia][][mia, [vincent, jules], [butch, girlfriend(butch)]][[], dead(zed), [2, [b, chopper]], [], Z, [2, [b, chopper]]]
ListsWe can specify lists in Prolog by enclosing the elements of the list in square brackets(that is, the symbols [ and ]). The elements are separated by commas.All sorts of Prolog objects can be elements of a list and the same item may occur more than once in the same list.The empty list(as its name suggests) is the list that contains no elements.lists can contain other lists as elements.Any non-empty list can be thought of as consisting of twoparts: the head and the tail. The head is simply the first item in the list; the tail is everything else.
MembersMember is a fundamental Prolog tool for manipulating lists, and to introduce the idea of recursing down lists.consider a program that, when given as inputs an arbitrary object X and a list L, tells us whether or not X belongs to L. The program that does this is usually called member. Here it is:member(X,[X|T]).member(X,[H|T]) :- member(X,T).one fact (namely member(X,[X|T])) and one rule (namely member(X,[H|T]) :- member(X,T)). But note that the rule is recursive (after all, the functor member occurs in both the rule's head and tail)
MembersSuppose we posed the following query:? -member(yolanda,[yolanda,trudy,vincent,jules]).Prolog will immediately answer `Yes'. Because it can unify yolanda with both occurrences of X in the first clause (the fact) in the definition of member/2, so it succeeds immediately.
Recursing Down ListsMember works by recursively working down a list, doing something to the head, and then recursively doing the same thing to the tail. Recursing down a list (or indeed, several lists) in this way is extremely common in Prolog.When working with lists, we often want to compare one list with another, or to copy bits of one list into another, or to translate the contents of one list into another, or something similar.Ex:  Let's suppose we need a predicate a2b/2 that takes two lists as arguments, and succeeds if the first argument is a list of as, and the second argument is a list of bs of exactly the same length.If we pose the following querya2b([a,a,a,a],[b,b,b,b]).we want Prolog to say `yes'.
Recursing Down ListsIf we pose the querya2b([a,a,a,a],[b,b,b]) or the querya2b([a,c,a,a],[b,b,5,4]).we want Prolog to say `no'.For longer lists, think recursively. So when should a2b/2 decide that two non-empty lists are a list of as and a list of bs of exactly the same length?
Simple: when the head of the first list is an a, and the head of the second list is a b, and a2b/2 decides that the two tails are lists of as and bs of exactly the same length! This immediately gives us the following rule:a2b([a|Ta],[b|Tb]) :- a2b(Ta,Tb).The a2b/2 predicate should succeed if its first argument is a list with head a, its second argument is a list with head b, and a2b/2 succeeds on the two tails.Now, this definition make good sense declaratively.
Visit more self help tutorialsPick a tutorial of your choice and browse through it at your own pace.The tutorials section is free, self-guiding and will not involve any additional support.Visit us at www.dataminingtools.net
PROLOG: Recursion And Lists In Prolog

More Related Content

PPT
Prolog programming
PPTX
Planning
PPT
Greedy algorithms
PPTX
Reader/writer problem
PPT
Medians and order statistics
PPT
Context free grammars
PPTX
push down automata
PPTX
sum of subset problem using Backtracking
Prolog programming
Planning
Greedy algorithms
Reader/writer problem
Medians and order statistics
Context free grammars
push down automata
sum of subset problem using Backtracking

What's hot (20)

PPTX
Dfs presentation
PPT
Bfs and dfs in data structure
PPT
Backtracking Algorithm.ppt
PPT
SINGLE SOURCE SHORTEST PATH.ppt
PPT
Backtracking
PPTX
ProLog (Artificial Intelligence) Introduction
PPT
Planning
PPT
Graph traversal-BFS & DFS
PDF
Parse Tree
PDF
Approximation Algorithms
PPT
Graphs In Data Structure
PPTX
Artificial Intelligence (AI) | Prepositional logic (PL)and first order predic...
PPTX
Deductive databases
PPT
Breadth first search and depth first search
PDF
Interconnection Network
PPT
pushdown automata
PPTX
Kruskal's algorithm
PPTX
Kruskal Algorithm
PPTX
8 QUEENS PROBLEM.pptx
PPT
Free space managment46
Dfs presentation
Bfs and dfs in data structure
Backtracking Algorithm.ppt
SINGLE SOURCE SHORTEST PATH.ppt
Backtracking
ProLog (Artificial Intelligence) Introduction
Planning
Graph traversal-BFS & DFS
Parse Tree
Approximation Algorithms
Graphs In Data Structure
Artificial Intelligence (AI) | Prepositional logic (PL)and first order predic...
Deductive databases
Breadth first search and depth first search
Interconnection Network
pushdown automata
Kruskal's algorithm
Kruskal Algorithm
8 QUEENS PROBLEM.pptx
Free space managment46
Ad

Similar to PROLOG: Recursion And Lists In Prolog (20)

DOCX
AI Lab Manual.docx
PPTX
PROLOG: Introduction To Prolog
PPT
Section3 Prologppt
PDF
Prolog,Prolog Programming IN AI.pdf
PPT
Chaps 1-3-ai-prolog
PPTX
PROLOG: Arithmetic Operations In Prolog
PPTX
Prolog: Arithmetic Operations In Prolog
PPT
Inteligencia artificial
PDF
APAL2032
PPT
Pl vol1
PDF
Real World Haskell: Lecture 2
PDF
PPT
Pl vol1
PPTX
PPTX
First order logic in artificial Intelligence.pptx
PDF
English for Math Pertemuan ke 11
PPT
Chaps 1-3-ai-prolog
PDF
Meta-theory of Actions: Beyond Consistency
PDF
I am kind of confused about quantifiers. I am not sure how to transl.pdf
PDF
A course on mathematical logic
AI Lab Manual.docx
PROLOG: Introduction To Prolog
Section3 Prologppt
Prolog,Prolog Programming IN AI.pdf
Chaps 1-3-ai-prolog
PROLOG: Arithmetic Operations In Prolog
Prolog: Arithmetic Operations In Prolog
Inteligencia artificial
APAL2032
Pl vol1
Real World Haskell: Lecture 2
Pl vol1
First order logic in artificial Intelligence.pptx
English for Math Pertemuan ke 11
Chaps 1-3-ai-prolog
Meta-theory of Actions: Beyond Consistency
I am kind of confused about quantifiers. I am not sure how to transl.pdf
A course on mathematical logic
Ad

More from DataminingTools Inc (20)

PPTX
Terminology Machine Learning
PPTX
Techniques Machine Learning
PPTX
Machine learning Introduction
PPTX
Areas of machine leanring
PPTX
AI: Planning and AI
PPTX
AI: Logic in AI 2
PPTX
AI: Logic in AI
PPTX
AI: Learning in AI 2
PPTX
AI: Learning in AI
PPTX
AI: Introduction to artificial intelligence
PPTX
AI: Belief Networks
PPTX
AI: AI & Searching
PPTX
AI: AI & Problem Solving
PPTX
Data Mining: Text and web mining
PPTX
Data Mining: Outlier analysis
PPTX
Data Mining: Mining stream time series and sequence data
PPTX
Data Mining: Mining ,associations, and correlations
PPTX
Data Mining: Graph mining and social network analysis
PPTX
Data warehouse and olap technology
PPTX
Data Mining: Data processing
Terminology Machine Learning
Techniques Machine Learning
Machine learning Introduction
Areas of machine leanring
AI: Planning and AI
AI: Logic in AI 2
AI: Logic in AI
AI: Learning in AI 2
AI: Learning in AI
AI: Introduction to artificial intelligence
AI: Belief Networks
AI: AI & Searching
AI: AI & Problem Solving
Data Mining: Text and web mining
Data Mining: Outlier analysis
Data Mining: Mining stream time series and sequence data
Data Mining: Mining ,associations, and correlations
Data Mining: Graph mining and social network analysis
Data warehouse and olap technology
Data Mining: Data processing

Recently uploaded (20)

PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Empathic Computing: Creating Shared Understanding
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Advanced Soft Computing BINUS July 2025.pdf
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
Spectral efficient network and resource selection model in 5G networks
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Electronic commerce courselecture one. Pdf
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
madgavkar20181017ppt McKinsey Presentation.pdf
NewMind AI Monthly Chronicles - July 2025
Empathic Computing: Creating Shared Understanding
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Advanced Soft Computing BINUS July 2025.pdf
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
20250228 LYD VKU AI Blended-Learning.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Spectral efficient network and resource selection model in 5G networks

PROLOG: Recursion And Lists In Prolog

  • 2. OVERVIEWRecursive definitionsClause ordering, goal ordering, and termination.ListsMembersRecursing Down Lists
  • 3. Recursive definitionsA predicate is recursively defined if one or more rules in its definition refers to itself.Ex: is_digesting(X,Y) :- just_ate(X,Y).is_digesting(X,Y) :-just_ate(X,Z),is_digesting(Z,Y).just_ate(mosquito,blood(john)).just_ate(frog,mosquito).just_ate(stork,frog). It's just a knowledge base containing two facts andtwo rules. But the definition of the is_digesting/2 predicate is recursive.
  • 4. Another way of writing numerals, which is sometimes used in mathematical logic is to makes use of just four symbols: 0, succ, and the left and right brackets. This style of numeral is defined by the following inductive definition:1. 0 is a numeral.2. If X is a numeral, then so is succ(X).This definition in prolog program is written as:numeral(0).numeral(succ(X)) :- numeral(X).So, on posing the query numeral(succ(succ(succ(0)))).We get Yes.Now on running the following querynumeral(X).we can have the following dialogue with Prolog:X = 0 ;X = succ(0) ;X = succ(succ(0)) ;X = succ(succ(succ(0))) ;X = succ(succ(succ(succ(0)))) ;X = succ(succ(succ(succ(succ(0))))) ;X = succ(succ(succ(succ(succ(succ(0)))))) ;X = succ(succ(succ(succ(succ(succ(succ(0))))))) ;X = succ(succ(succ(succ(succ(succ(succ(succ(0)))))))) ;X = succ(succ(succ(succ(succ(succ(succ(succ(succ(0))))))))) ;X = succ(succ(succ(succ(succ(succ(succ(succ(succ(succ(0))))))))))YesIt's backtracking through the recursive definition, and actually building numerals using matching.
  • 5. Clause ordering, goal ordering, and terminationConsider the following ex:child(martha,charlotte).child(charlotte,caroline).child(caroline,laura).child(laura,rose).descend(X,Y) :- child(X,Y).descend(X,Y) :- child(X,Z),descend(Z,Y).We'll make two changes to it, and call the result descend2.pl:child(martha,charlotte).child(charlotte,caroline).child(caroline,laura).child(laura,rose).descend(X,Y) :- descend(Z,Y),child(X,Z).descend(X,Y) :- child(X,Y).
  • 6. we have merely reversed the order of the two rules, and reversed the order of the two goals in the recursive clause. So, viewed as a purely logical definition, nothing has changed.But the procedural meaning has changed dramatically. For example, if you pose the querydescend(martha,rose).you will get an error message (`out of local stack', or something similar).Because descend1.pl and descend2.pl are Prolog knowledge bases with the same declarative meaning but different procedural meanings: from a purely logical perspective they are identical, but they behave very differently.
  • 7. The declarative and procedural meanings of a Prolog program can differ, when writing Prolog programs you need to bear both aspects in mind.When you need to think about how Prolog will actually evaluate queries. The following questions must be considered:Are the rule orderings sensible? How will the program actually run?
  • 8. Listslists, an important recursive data structure widely used in computational linguistics.It is a finite sequence of elements. Here are some examples of lists in Prolog:[mia, vincent, jules, yolanda][mia, robber(honey_bunny), X, 2, mia][][mia, [vincent, jules], [butch, girlfriend(butch)]][[], dead(zed), [2, [b, chopper]], [], Z, [2, [b, chopper]]]
  • 9. ListsWe can specify lists in Prolog by enclosing the elements of the list in square brackets(that is, the symbols [ and ]). The elements are separated by commas.All sorts of Prolog objects can be elements of a list and the same item may occur more than once in the same list.The empty list(as its name suggests) is the list that contains no elements.lists can contain other lists as elements.Any non-empty list can be thought of as consisting of twoparts: the head and the tail. The head is simply the first item in the list; the tail is everything else.
  • 10. MembersMember is a fundamental Prolog tool for manipulating lists, and to introduce the idea of recursing down lists.consider a program that, when given as inputs an arbitrary object X and a list L, tells us whether or not X belongs to L. The program that does this is usually called member. Here it is:member(X,[X|T]).member(X,[H|T]) :- member(X,T).one fact (namely member(X,[X|T])) and one rule (namely member(X,[H|T]) :- member(X,T)). But note that the rule is recursive (after all, the functor member occurs in both the rule's head and tail)
  • 11. MembersSuppose we posed the following query:? -member(yolanda,[yolanda,trudy,vincent,jules]).Prolog will immediately answer `Yes'. Because it can unify yolanda with both occurrences of X in the first clause (the fact) in the definition of member/2, so it succeeds immediately.
  • 12. Recursing Down ListsMember works by recursively working down a list, doing something to the head, and then recursively doing the same thing to the tail. Recursing down a list (or indeed, several lists) in this way is extremely common in Prolog.When working with lists, we often want to compare one list with another, or to copy bits of one list into another, or to translate the contents of one list into another, or something similar.Ex: Let's suppose we need a predicate a2b/2 that takes two lists as arguments, and succeeds if the first argument is a list of as, and the second argument is a list of bs of exactly the same length.If we pose the following querya2b([a,a,a,a],[b,b,b,b]).we want Prolog to say `yes'.
  • 13. Recursing Down ListsIf we pose the querya2b([a,a,a,a],[b,b,b]) or the querya2b([a,c,a,a],[b,b,5,4]).we want Prolog to say `no'.For longer lists, think recursively. So when should a2b/2 decide that two non-empty lists are a list of as and a list of bs of exactly the same length?
  • 14. Simple: when the head of the first list is an a, and the head of the second list is a b, and a2b/2 decides that the two tails are lists of as and bs of exactly the same length! This immediately gives us the following rule:a2b([a|Ta],[b|Tb]) :- a2b(Ta,Tb).The a2b/2 predicate should succeed if its first argument is a list with head a, its second argument is a list with head b, and a2b/2 succeeds on the two tails.Now, this definition make good sense declaratively.
  • 15. Visit more self help tutorialsPick a tutorial of your choice and browse through it at your own pace.The tutorials section is free, self-guiding and will not involve any additional support.Visit us at www.dataminingtools.net