我必须像这样合并列表的两个相等元素:
[1,2,3,4,5,5,6,7,5,6] => [1,2,3,4,55,6,7,5,6]
我怎么能在序言中做到这一点?谢谢大家。
滥用 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].
类似的东西?
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).