Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

couples 1

Status
Not open for further replies.

xristiana

Programmer
Oct 23, 2010
48
GR
Hi, I want to apologize to all and especially Mr. Kahleen for my continuous asking for help, but I have boggled.
Here's what I have to do next, I have a list A and a list B with the couples of the elements of list A, for example: list A=[4,5,6,7,8,9] and list B=[[4,5],[6,7],[8,9]].
I have made a programm, but the only thing it does when I insert a example, is true. Here it is:

couples([], _).
couples([H, H1|A], B) :- append([H], [H1], L), pair_list(A, [L|B]).

But it's wrong. The question is, what is the right one?
 
In the 2 elements list, B was []. Now, in the 4 elements list, B is [[6,7]] from the clause you made that I didn't understand. I also don't understand this:
"B is the result of couples([6, 7], B)."
I'm quite confused. :S
 
Code:
couples([], []).
couples([H, H1 | A], [[H, H1] | B]) :-
    couples(A, B).

When the second rule is used with [H, H1 | A] = [4, 5], then H = 4, H1 = 5 and A is [] and your result is [[H, H1] | B], so from the body of the rule you can see that couples is called again with A = [] and B unbound, so B would be the result of calling couples([], B), so B = [] from the first rule. Once you have B, your full result is [[H, H1] | B] which is [[4, 5]] if you use the variable values.

Now when the second rule is used with [H, H1 | A] = [4, 5, 6, 7], then H = 4, H1 = 5 and A = [6, 7] and your result is [[H, H1] | B], so from the body of the rule you can see that couples is called again with A = [6, 7] and B unbound, so B would be the result of calling couples([6, 7], B). When you have B, you put it in your full result which is [[H, H1] | B] and once you use the values you will have [[4, 5], [6, 7]].

I don't understand why you have so many problems understanding this, you should understand that in any call to couples(X, Y) X is the initial list and Y is the result. And our main rule states that if X is of the form [H, H1 | A] then Y is of the form [[H, H1] | B] where B is determined by calling again couples(A, B).
 
Ok, now I got it thanks. I didn't understand why B is [6,7], it's a little bit difficult, but now I get it. We use backtracking.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top