SlideShare a Scribd company logo
2
Most read
3
Most read
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

What's hot (20)

PPTX
Prolog 7-Languages
Pierre de Lacaze
 
PPTX
Artificial Intelligence (AI) | Prepositional logic (PL)and first order predic...
Ashish Duggal
 
PDF
record_linking
Robert Berry
 
PDF
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
PDF
haskell_fp1
Sambaiah Kilaru
 
PPT
Prolog 01
saru40
 
PPT
Prolog basics
shivani saluja
 
PDF
20130215 Reading data into R
Kazuki Yoshida
 
PDF
20130222 Data structures and manipulation in R
Kazuki Yoshida
 
PPT
Predlogic
saru40
 
PDF
Python for beginners
Ali Huseyn Aliyev
 
PDF
First order logic
Chinmay Patel
 
PDF
Reading Data into R
Kazuki Yoshida
 
PDF
Some alternative ways to find m ambiguous binary words corresponding to a par...
ijcsa
 
PPTX
Files,blocks and functions in R
Vladimir Bakhrushin
 
PPT
Discrete Math Lecture 01: Propositional Logic
IT Engineering Department
 
PPTX
The Bund language
Vladimir Ulogov
 
PPT
Pl vol1
Aarsh Ps
 
PPT
Inteligencia artificial
roxana24conamor
 
Prolog 7-Languages
Pierre de Lacaze
 
Artificial Intelligence (AI) | Prepositional logic (PL)and first order predic...
Ashish Duggal
 
record_linking
Robert Berry
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
haskell_fp1
Sambaiah Kilaru
 
Prolog 01
saru40
 
Prolog basics
shivani saluja
 
20130215 Reading data into R
Kazuki Yoshida
 
20130222 Data structures and manipulation in R
Kazuki Yoshida
 
Predlogic
saru40
 
Python for beginners
Ali Huseyn Aliyev
 
First order logic
Chinmay Patel
 
Reading Data into R
Kazuki Yoshida
 
Some alternative ways to find m ambiguous binary words corresponding to a par...
ijcsa
 
Files,blocks and functions in R
Vladimir Bakhrushin
 
Discrete Math Lecture 01: Propositional Logic
IT Engineering Department
 
The Bund language
Vladimir Ulogov
 
Pl vol1
Aarsh Ps
 
Inteligencia artificial
roxana24conamor
 

Viewers also liked (6)

PPT
Logic Programming and Prolog
Sadegh Dorri N.
 
PPT
Unit 3 principles of programming language
Vasavi College of Engg
 
PPTX
Prolog Programming : Basics
Mitul Desai
 
PPTX
Unit1 principle of programming language
Vasavi College of Engg
 
Logic Programming and Prolog
Sadegh Dorri N.
 
Unit 3 principles of programming language
Vasavi College of Engg
 
Prolog Programming : Basics
Mitul Desai
 
Unit1 principle of programming language
Vasavi College of Engg
 
Ad

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

DOCX
AI Lab Manual.docx
KPRevathiAsstprofITD
 
PPTX
PROLOG: Introduction To Prolog
DataminingTools Inc
 
PPT
Section3 Prologppt
Mariam asfour
 
PDF
Prolog,Prolog Programming IN AI.pdf
CS With Logic
 
PPT
Chaps 1-3-ai-prolog
juanpaperez1234
 
PPTX
Prolog: Arithmetic Operations In Prolog
PROLOG CONTENT
 
PPTX
PROLOG: Arithmetic Operations In Prolog
DataminingTools Inc
 
PDF
APAL2032
Dan HERNEST
 
PPT
Pl vol1
Aarsh Ps
 
PDF
Real World Haskell: Lecture 2
Bryan O'Sullivan
 
PDF
Notes8
Amba Research
 
PPTX
maths
noushidismail
 
PPTX
First order logic in artificial Intelligence.pptx
Y21IT051
 
PDF
English for Math Pertemuan ke 11
Amalia Indrawati Gunawan
 
PDF
Meta-theory of Actions: Beyond Consistency
Ivan Varzinczak
 
PDF
I am kind of confused about quantifiers. I am not sure how to transl.pdf
AMITPANCHAL154
 
PDF
A course on mathematical logic
Springer
 
PPTX
Lecture 09.pptx
Mohammad Hassan
 
PPT
Introduction to Python - Part Two
amiable_indian
 
PDF
Lambda Calculus by Dustin Mulcahey
Hakka Labs
 
AI Lab Manual.docx
KPRevathiAsstprofITD
 
PROLOG: Introduction To Prolog
DataminingTools Inc
 
Section3 Prologppt
Mariam asfour
 
Prolog,Prolog Programming IN AI.pdf
CS With Logic
 
Chaps 1-3-ai-prolog
juanpaperez1234
 
Prolog: Arithmetic Operations In Prolog
PROLOG CONTENT
 
PROLOG: Arithmetic Operations In Prolog
DataminingTools Inc
 
APAL2032
Dan HERNEST
 
Pl vol1
Aarsh Ps
 
Real World Haskell: Lecture 2
Bryan O'Sullivan
 
First order logic in artificial Intelligence.pptx
Y21IT051
 
English for Math Pertemuan ke 11
Amalia Indrawati Gunawan
 
Meta-theory of Actions: Beyond Consistency
Ivan Varzinczak
 
I am kind of confused about quantifiers. I am not sure how to transl.pdf
AMITPANCHAL154
 
A course on mathematical logic
Springer
 
Lecture 09.pptx
Mohammad Hassan
 
Introduction to Python - Part Two
amiable_indian
 
Lambda Calculus by Dustin Mulcahey
Hakka Labs
 
Ad

Recently uploaded (20)

PDF
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Français Patch Tuesday - Juillet
Ivanti
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
 
PDF
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 
NewMind AI Journal - Weekly Chronicles - July'25 Week II
NewMind AI
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Français Patch Tuesday - Juillet
Ivanti
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Building a Production-Ready Barts Health Secure Data Environment Tooling, Acc...
Barts Health
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Top Managed Service Providers in Los Angeles
Captain IT
 
Empowering Cloud Providers with Apache CloudStack and Stackbill
ShapeBlue
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
 

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