String Processing

I’m using: SWI-Prolog version 8.2.1

Hello.

In Java it is very easy:

String word = "asdHulofasdFado"

for-loop goes through an array:

the word gets manipulated by every entry of the array .. In prolog it would be a list.

first entry of array: Hulu Muba ..So replace hulo by Muba
Result: asdMubafasdFado

second entry of array: Fado Gedi
Result: asdMubafasdGedi

So every entry changes the word.

End for-loop.

The only problem I have is the variable word.
Somewhere I have to save it, so I can manipulate it.

I only know two methods: Traverse a List and loop

goThroughList([], []).
goThroughList([V|R], Z) :- 
   goThroughList(R, D),
   something(V, K),
   append(D,[K],Z).

And

loop(N, A , L) :- 
   ...,
   loop(S,  A ,R).

Both do not help to solve the problem. Because I cannot transfer the variable word.

Thank you

You don’t need append. You need an accumulator:

replace_all([], R, R).
replace_all([Pattern-With|Rest], S, R) :-
    re_replace(Pattern/g, With, S, R0),
    replace_all(Rest, R0, R).

You could also use foldl. Like this:

replace_all(Replacements, String, Result) :-
    foldl(replace, Replacements, String, Result).

replace(Pattern-With, String, Result) :-
    re_replace(Pattern/g, With, String, Result).
?- replace_all(["Hulo"-"Muba", "Fado"-"Gedi"], "asdHulofasdFado", Result).
Result = "asdMubafasdGedi".
1 Like

Thank you. It solved the problem perfectly. Never heard of foldl before.