作为对此提出问题的question的后续措施
返回列表中的项目计数,但是如果两个相同的项目彼此相邻,则不要增加计数。
这段代码是我使用DCG和半上下文解决此问题最接近的代码。
lookahead(C),[C] -->
[C].
% empty list
% No lookahead needed because last item in list.
count_dcg(N,N) --> [].
% single item in list
% No lookahead needed because only one in list.
count_dcg(N0,N) -->
[_],
\+ [_],
{ N is N0 + 1 }.
% Lookahead needed because two items in list and
% only want to remove first item.
count_dcg(N0,N) -->
[C1],
lookahead(C2),
{ C1 == C2 },
count_dcg(N0,N).
% Lookahead needed because two items in list and
% only want to remove first item.
count_dcg(N0,N) -->
[C1],
lookahead(C2),
{
C1 \== C2,
N1 is N0 + 1
},
count_dcg(N1,N).
count(L,N) :-
DCG = count_dcg(0,N),
phrase(DCG,L).
想知道是否有可能在子句头上使用半上下文进行更改,例如
count_dcg(N0,N),[C] -->
[C,C],
count_dcg(N0,N).
如果可能,那么需要工作示例代码,如果不可能,则需要说明。