4.5 Practical Session
The purpose of Practical Session 4 is to help you get familiar with the idea of recursing down lists. We first suggest some traces for you to carry out, and then some programming exercises.
First, systematically carry out a number of traces on a2b/2 to make sure you fully understand how it works. In particular:
- Trace some examples, not involving variables, that succeed. For example, trace the query a2b([a,a,a,a],[b,b,b,b]) and relate the output to the discussion in the text.
- Trace some simple examples that fail. Try examples involving lists of different lengths (such as a2b([a,a,a,a],[b,b,b]) ) and examples involving symbols other than a and b (such as a2b([a,c,a,a],[b,b,5,4]) ).
- Trace some examples involving variables. For example, try tracing a2b([a,a,a,a],X) and a2b(X,[b,b,b,b]) .
- Make sure you understand what happens when both arguments in the query are variables. For example, carry out a trace on the query a2b(X,Y) .
- Carry out a series of similar traces involving member/2 . That is, carry out traces involving simple queries that succeed (such as member(a,[1,2,a,b]) ), simple queries that fail (such as member(z,[1,2,a,b]) ), and queries involving variables (such as member(X,[1,2,a,b]) ). In all cases, make sure that you understand why the recursion halts.
Having done this, try the following.
- Write a 3-place predicate
combine1
which takes three lists as arguments and combines the elements of the first two lists into the third as follows:
?- combine1([a,b,c],[1,2,3],X). X = [a,1,b,2,c,3] ?- combine1([f,b,yip,yup],[glu,gla,gli,glo],Result). Result = [f,glu,b,gla,yip,gli,yup,glo]
- Now write a 3-place predicate
combine2
which takes three lists as arguments and combines the elements of the first two lists into the third as follows:
?- combine2([a,b,c],[1,2,3],X). X = [[a,1],[b,2],[c,3]] ?- combine2([f,b,yip,yup],[glu,gla,gli,glo],Result). Result = [[f,glu],[b,gla],[yip,gli],[yup,glo]]
- Finally, write a 3-place predicate
combine3
which takes three lists as arguments and combines the elements of the first two lists into the third as follows:
?- combine3([a,b,c],[1,2,3],X). X = [j(a,1),j(b,2),j(c,3)] ?- combine3([f,b,yip,yup],[glu,gla,gli,glo],R). R = [j(f,glu),j(b,gla),j(yip,gli),j(yup,glo)]
All three programs are pretty much the same as a2b/2 (though they manipulate three lists, not two). That is, all three can be written by recursing down the lists, doing something to the heads, and then recursively doing the same thing to the tails. Indeed, once you have written combine1 , you just need to change what you do to the heads to get combine2 and combine3 .