I am trying to learn Prolog. I have a problem and the solution for that in Prolog. Though I am unable to understand the code completely.
The call of the code goes like this-
conc(Before,[c|After],[a,b,c,d]) .
This code will return
Before = [a,b]
After = [d]
I have the solution -
conc([],L,L).
conc([X|L1],L2,[X|L3]) :- conc(L1,L2,L3) .
I am not able to understand the flow of the program completely. Let me start with a dry run. I added some write command in order understand the code flow. The code now looks like this -
conc([],L,L):- write("Line1: "), write(L).
conc([X|L1],L2,[X|L3]) :-
write("Line-2: "), write(L1), write(" "),
write(L2), write(" "), write(L3), conc(L1,L2,L3) .
Initial call is -
conc(Before,[c|After],[a,b,c,d]) .
At this moment, the call goes to line 2 (because, Before is unknown term which is not empty)which is :
conc([X|L1],L2,[X|L3]) :-
write("Line-2: "), write(L1), write(" "),
write(L2), write(" "), write(L3), conc(L1,L2,L3) .
At this point, X=[a], l1= unknown, L2=[c|After] and L3=[b,c,d]. This prints -
Line2: _G481 [c|_G368] [b,c,d]
This will again call the recursion(code line 2) with the following value:
cons(L1, [c|After], [b,c,d]). (L1 is unknown still now)
And, prints -
Line2: _G494 [c|_G368] [c,d]
Now the next call will be :
cons(L1, [c|After], [c,d]).
But , I can see while printing the customized comments in the code, that, at this point the code control goes to #line 1 which I am not able to understand. Because, now,
L1= unknown(just as all the previous calls).
L(parameter 2)= [c|After]
L(parameter 3) = [c,d].
But, the control goes to the #line 1, and it prints :
Line1: [c,d]
I thought prolog executes the code from left to right. So, as per my understanding, while executing the value of L should be [c,d].
My question is:
1. After the second call, L1 is undefined as all the calls as before. And, second and third parameters , both are L. So, why, after second call the control goes to the #line1.?
2. Is my understanding correct in this matter ? "I thought prolog executes the code from left to right. So, as per my understanding, while executing the value of L should be [c,d]."
Thanks in advance... Please help me out!!