Download Recursion-Data Structures-Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!
30/09/04 1
Recursion
- When a predicate calls itself within its body we say
the clause is recursing
1) drinks(alan,juice).
2) likes(alan,coffee).
3) likes(heather,coffee).
4) likes(Person,Drink):-
drinks(Person,Drink).
5) likes(Person,Somebody):-
likes(Person,Drink),
likes(Somebody,Drink).
30/09/04 2
Why use recursion?
- It allows us to define very clear and elegant code.
- Why repeat code when you can reuse existing code.
- Relationships may be recursive
e.g. “X is my brother if X is my brother‟s brother.”
- Data is represented recursively and best processed
iteratively.
- Grammatical structures can contain themselves
- Ordered data: each element requires the same processing
- Allows Prolog to perform complex search of a
problem space without any dedicated algorithms.
30/09/04 4
Structure unification
- 2 structures will unify if
- the functors are the same,
- they have the same number of components,
- and all the components unify.
| ?- person(Nm,london,Age) = person(bob,london,48). Nm = bob, Age = 48? yes | ?- person(Someone,_,45) = person(harry,dundee,45). Someone = harry? yes
- (A plain underscore „_‟ is not bound to any value. By using it you
are telling Prolog to ignore this argument and not report it.)
30/09/04 5
Structure unification (2)
- A structure may also have another structure as a
component.
|?-addr(flat(4),street(‘Home Str.’),postcode(eh8_9lw))
= addr(flat(Z),Yy,postcode(Xxx)). Z = 4, Yy = street(‘Home Str.’), Xxx = eh8_9lw? yes
- Unification of nested structures
works recursively:
- first it unifies the entire structure,
- then it tries to unify the nested structures.
Remember to close brackets!
Reported variables are ordered according to number of characters in the variable name.
30/09/04 7
Lists
- A collection of ordered data.
- Has zero or more elements enclosed by square
brackets („[ ]‟) and separated by commas („,‟).
[a] a list with one element
[] an empty list
1 2 3 1 2
[34,tom,[2,3]] a list with 3 elements where the
3 rd^ element is a list of 2 elements.
- Like any object, a list can be unified with a variable
|?- [Any, list, ‘of elements’] = X. X = [Any, list, ‘of elements’]? yes
30/09/04 8
List Unification
- Two lists unify if they are the same length and all their
elements unify.
|?-[a,B,c,D]=[A,b,C,d]. |?-[(a+X),(Y+b)]=[(W+c),(d+b)].
A = a, W = a,
B = b, X = c,
C = c, Y = d?
D = d? yes
yes
|?- [[X,a]]=[b,Y]. |?-[[a],[B,c],[]]=[X,[b,c],Y].
no B = b,
X = [a], Y = []? yes
Length 1 Length 2
30/09/04 10
Head and Tail
|?-[a,b,c,d]=[Head|Tail]. |?-[a,b,c,d]=[X|[Y|Z]]. Head = a, X = a, Tail = [b,c,d]? Y = b, yes Z = [c,d]; yes
|?-[a] = [H|T]. |?-[a,b,c]=[W|[X|[Y|Z]]]. H = a, W = a, T = []; X = b, yes Y = c, Z = []? yes
|?-[] = [H|T]. |?-[a|[b|[c|[]]]]= List. no List = [a,b,c]? yes