我必须合并列表中的两个相等元素,如下所示:
[1,2,3,4,5,5,6,7,5,6] => [1,2,3,4,55,6,7,5,6]
我怎么能在prolog中这样做?谢谢大家。
答案 0 :(得分:1)
那样的东西?
my_merge(N, L, R) :-
merge(N, L, [], R).
merge(_, [], R, R1) :-
reverse(R, R1).
merge(N, [M | T], CR, FR) :-
N \= M,
merge(N, T, [M |CR], FR).
merge(N, [N | T], CR, FR) :-
merge_(N, T, N, CR, FR).
merge_(N, [M| T], X, CR, FR) :-
M \= N,
merge(N, [M | T], [X | CR], FR).
merge_(N, [N| T], X, CR, FR) :-
X1 is X * 10 + N,
merge_(N, T, X1, CR, FR).
merge_(_N, [], X, CR, FR) :-
reverse([X | CR], FR).
答案 1 :(得分:1)
滥用Prolog灵活的数据表示,我们可以这样做:
fuse_consec([E,E|L], E, [N|F]) :-
!, fuse_consec([E|L], E, [R|F]),
atom_concat(E, R, C),
atom_number(C, N).
fuse_consec([X|L], E, [X|F]) :-
fuse_consec(L, E, F).
fuse_consec([], _, []).
测试
?- fuse_consec([1,2,3,4,5,5,6,7,5,6],5,L).
L = [1, 2, 3, 4, 55, 6, 7, 5, 6].