Replacing substring in second occurrence in prolog

时间:2018-07-24 10:07:20

标签: string recursion replace prolog

First of all, this is not a homework. I'm studying Computer Sciences in my home, to learn a little more alone.

I'm doing an excercise. It says like this:

Construct a predicate called replaceAtomsString/4 so that given a string s as the first parameter, a number N as the second parameter, and a pair of atoms [g, h] (list) as the third parameter, unify in a fourth parameter the replacement in the Nth apparition of g in s replacing it by h. Example:

replaceAtomsString (sAbbbsAbbasA, 2, [sA, cc], X) should result in

X = sAbbbccbbasA

So, my first approach was trying to build a list with the string, just like prolog do with every string. After all, i've built this code:

substitute(X, S, T, Y) :-
    append(S, Xt, X), % i.e. S is the first part of X, the rest is Xt
    !,
    substitute(Xt, S, T, Yt),
    append(T, Yt, Y).
substitute([Xh|Xt], S, T, [Xh|Yt]) :-
    substitute(Xt, S, T, Yt).

But it returns false on every attempt.

Any ideas?

1 个答案:

答案 0 :(得分:1)

由于需要大量工作才能完成代码,因此以下是使用可用库执行任务的方法。

sub_atom / 5这是处理原子的强大谓词。与call_nth / 2结合使用,该解决方案比编码围绕N的循环所产生的结果更直接,更通用。

replaceAtomsString(S,N,[G,H],X) :-
    call_nth(sub_atom(S,Before,_,After,G),N),
    sub_atom(S,0,Before,_,Left),
    sub_atom(S,_,After,0,Right),
    atomic_list_concat([Left,H,Right],X).

示例运行查询,但保留N进行计算:

?- replaceAtomsString(sAbbbsAbbasA, N, [sA, cc], X).
N = 1,
X = ccbbbsAbbasA ;
N = 2,
X = sAbbbccbbasA ;
N = 3,
X = sAbbbsAbbacc ;
false.