I've got a Prolog
exercise that requires me to count how many time a list L2
appears as a sublist in L1
.
What I need to do is to write the Prolog
code starting from the code written in another language (some kind of didactic puropose language that we use in my university).
So I wrote the algorithm is this language and everything works smooth, but the Prolog
version fails and I don't undertand why.
The idea is quite simple:
- Get the length of
L2
and call itSizeL2
- Starting from the head of L1, get each sublist of size
SizeL2
. - Check if
subList(L1, SizeL2)==L2
and add 1 if true - When the end of
L1
is reached, we returncount
This means something like:
L1=[1,2,3,4,5,2,3,2,3,4], L2=[2,3,4], SizeL2=3, count=0
Step 1 -> [1,2,3]
Step 2 -> [2,3,4] - true, count+1
Step 3 -> [3,4,5]
Step 4 -> [4,5,2]
Step 5 -> [5,2,3]
Step 6 -> [2,3,2]
Step 7 -> [3,2,3]
Step 8 -> [2,3,4] - true, count+1
Step 9 -> L1 is finished, return 2
Now, this is how I translated it to Prolog
.
Please note that I've got to avoid any kind of system predicate!
%% we get the size of a list
size([], 0):-!.
size([H|T], R):- size(T,R1), R is R1+1.
%% we get the sublist of the given size
subList(_, 0, []):-!. %% if size is 0, we return an empty list
subList([], _, []):-!. %% if the list is empty, we're done
subList([H|T], Size, [H|Tr]):- Size1 is Size-1,
subList(T, Size1, Tr).
%% we count how many times L2 is sublist of L1
countSublist([], _, 0):-!. %% if L1 is empty we return 0
countSublist(L1, L2, 0):- size(L1, S1),
size(L2, S2),
S1 < S2. %% if L1 is shorter than L2, we return 0
countSublist([H|T], L2, R):- size(L2, SizeL2), %% we need L2's size
subList([H|T], SizeL2, SubL1), %% we get L1's sublist
countSublist(T, L2, R),
SubL1 = L2,
R1 is R+1. %% we do R+1 only if L2=Sublist of L1
The translation from our language is quite straight-forward and I'm sure that I did it correctly, but I still don't understand why the Prolog
versione doesn't work.
I think that the problem should be in the last predicate (countSublist([H|T], L2, R)
) because size
and subList
are working fine.
Any idea?