Hello.
?- teto("abab", "cc","ababvvvababeeeeababtttttabab", R).
I get the output: But only thanks to write(Q)
.
[c,c,v,v,v,a,b,a,b,e,e,e,e,a,b,a,b,t,t,t,t,t,a,b,a,b]
[c,c,v,v,v,c,c,e,e,e,e,a,b,a,b,t,t,t,t,t,a,b,a,b]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,a,b,a,b]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,c,c,e,e,e,e,a,b,a,b,t,t,t,t,t,c,c]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,a,b,a,b,e,e,e,e,c,c,t,t,t,t,t,a,b,a,b]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,a,b,a,b]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,a,b,a,b,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,a,b,a,b,e,e,e,e,a,b,a,b,t,t,t,t,t,c,c]
[c,c,v,v,v,c,c,e,e,e,e,a,b,a,b,t,t,t,t,t,c,c]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,a,b,a,b,e,e,e,e,c,c,t,t,t,t,t,c,c]
[c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
But I only want the following output: R = [c,c,v,v,v,c,c,e,e,e,e,c,c,t,t,t,t,t,c,c]
I tried it without write. I get only false
. And I tried append
and other tricks. But it returns always false
.
% here I start the program.
With count_substring
I know how many times the substring is in the string. So I know how often the loop has to run to replace all substring entries.
teto(Ag, B,Z, R) :-
count_substring(Z,Ag,X),
stringToList(Ag,U),
stringToList(B,E),
stringToList(Z,J),
loop(U,E,J, R, X ).
% just base cases
loop(Ag, B,Z, Xs, 0) :- not(replacement(Ag, B, Z, Xs)), !.
loop(Ag, B,Z, Xs, 0) :- replacement(Ag, B, Z, Xs), !.
% loops till N is 0, replaces every substring "abab" with "cc" in the string:
"ababvvvababeeeeababtttttabab"
loop(Ag, B,Z, W, N) :-
N>0,
S is N-1,
loop(Ag, B, Z,Q, S),
write(Q), nl,
replacement(Ag, B, Q, W).
% count the number of substring in the string
count_substring(String, Sub, Total) :-
count_substring(String, Sub, 0, Total).
count_substring(String, Sub, Count, Total) :-
( substring_rest(String, Sub, Rest)
->
succ(Count, NextCount),
count_substring(Rest, Sub, NextCount, Total)
;
Total = Count
).
substring_rest(String, Sub, Rest) :-
sub_string(String, Before, Length, Remain, Sub),
DropN is Before + Length,
sub_string(String, DropN, Remain, 0, Rest).
% convert strint to list and flatten it ,, because replacement accepts only lists
stringToList(L,Y) :-
atom_codes(A, L),
atom_chars(A, K),
flatten(K, Y).
% replace in a list [a,b,a,b,v,v,v,a,b,a,b] a list entry [a,b,a,b] with another list [c,c]
replacement(A, B, Ag, Bg) :-
phrase((seq(S1),seq(A),seq(S2)), Ag),
phrase((seq(S1),seq(B),seq(S2)), Bg).
seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).
Thank you.