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

PPTX
0 1 knapsack using branch and bound
PPTX
Reasoning in AI
PPTX
Divide and conquer - Quick sort
PPT
Chapter 5 Syntax Directed Translation
PDF
First order logic
PPTX
Forward and Backward chaining in AI
PPTX
Np hard
PPTX
Knowledge representation in AI
0 1 knapsack using branch and bound
Reasoning in AI
Divide and conquer - Quick sort
Chapter 5 Syntax Directed Translation
First order logic
Forward and Backward chaining in AI
Np hard
Knowledge representation in AI

What's hot (20)

PDF
AI PPT-ALR_Unit-3-1.pdf
PPTX
The Wumpus World in Artificial intelligence.pptx
PPTX
ProLog (Artificial Intelligence) Introduction
PDF
P, NP, NP-Complete, and NP-Hard
PDF
Symbol table in compiler Design
PPT
Branch and bound
PPTX
Knapsack Problem
PPT
BackTracking Algorithm: Technique and Examples
PPT
Dinive conquer algorithm
PPTX
Artificial Intelligence Notes Unit 3
PPTX
Resolution method in AI.pptx
PDF
Algorithms Lecture 8: Pattern Algorithms
PPT
Intermediate code generation (Compiler Design)
PDF
UNIT-V.pdf daa unit material 5 th unit ppt
PDF
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
PPT
Randomized algorithms ver 1.0
PPTX
Strassen's matrix multiplication
PPTX
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
PPT
Medians and order statistics
PPTX
Scalable community detection with the louvain algorithm
AI PPT-ALR_Unit-3-1.pdf
The Wumpus World in Artificial intelligence.pptx
ProLog (Artificial Intelligence) Introduction
P, NP, NP-Complete, and NP-Hard
Symbol table in compiler Design
Branch and bound
Knapsack Problem
BackTracking Algorithm: Technique and Examples
Dinive conquer algorithm
Artificial Intelligence Notes Unit 3
Resolution method in AI.pptx
Algorithms Lecture 8: Pattern Algorithms
Intermediate code generation (Compiler Design)
UNIT-V.pdf daa unit material 5 th unit ppt
Perspective in Informatics 3 - Assignment 2 - Answer Sheet
Randomized algorithms ver 1.0
Strassen's matrix multiplication
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
Medians and order statistics
Scalable community detection with the louvain algorithm
Ad

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

DOCX
AI Lab Manual.docx
PPTX
PROLOG: Introduction To Prolog
PPT
Chaps 1-3-ai-prolog
PPT
Prolog programming
PPT
Prolog programming
PPT
Prolog programming
PPT
Prolog programming
PPT
Prolog programming
PPT
Prolog programming
PPT
Prolog programming
PDF
"That scripting language called Prolog"
PPTX
Prolog 7-Languages
PPT
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
PPTX
Introduction to Prolog
PPTX
Prolog -Cpt114 - Week3
PPTX
Introduction on Prolog - Programming in Logic
PDF
Prolog,Prolog Programming IN AI.pdf
PPTX
List manipulation
PPTX
Prolog language programming in the facts.pptx
PPT
09 logic programming
AI Lab Manual.docx
PROLOG: Introduction To Prolog
Chaps 1-3-ai-prolog
Prolog programming
Prolog programming
Prolog programming
Prolog programming
Prolog programming
Prolog programming
Prolog programming
"That scripting language called Prolog"
Prolog 7-Languages
PROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOGPROLOG
Introduction to Prolog
Prolog -Cpt114 - Week3
Introduction on Prolog - Programming in Logic
Prolog,Prolog Programming IN AI.pdf
List manipulation
Prolog language programming in the facts.pptx
09 logic programming
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)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Approach and Philosophy of On baking technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Machine learning based COVID-19 study performance prediction
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Electronic commerce courselecture one. Pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
“AI and Expert System Decision Support & Business Intelligence Systems”
Approach and Philosophy of On baking technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Machine learning based COVID-19 study performance prediction
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
cuic standard and advanced reporting.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Understanding_Digital_Forensics_Presentation.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
The Rise and Fall of 3GPP – Time for a Sabbatical?
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Reach Out and Touch Someone: Haptics and Empathic Computing
Diabetes mellitus diagnosis method based random forest with bat algorithm
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Electronic commerce courselecture one. Pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...

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