0

当给定一些输入列表时,我想构建一个新列表,它应该:

  • 始终在新列表前面添加 h
  • 比较输入列表的每两个连续元素,如果它们相等,则将 y 附加到新列表中,如果不相等,则附加 x。

例子:

?- control([a,a,b,b],R).
R = [h,y,x,y].

到目前为止,这是我的代码:

control([H,H|T],K,[K,0|T2]):- control([H|T],[K,0],T2).
control([H,J|T],K,[K,1|T2]):- control([J|T],[K,1],T2).
control([H],G,G).

但它不能正常工作。

?-  control([a,a,b,b],[h],L).
L = [[h], 0, [[h], 0], 1, [[[h], 0], 1], 0, [[[...]|...], 1], 0] ;
L = [[h], 0, [[h], 0], 1, [[[h], 0], 1], 1, [[[...]|...], 1], 1] ;
L = [[h], 1, [[h], 1], 1, [[[h], 1], 1], 0, [[[...]|...], 1], 0] ;
L = [[h], 1, [[h], 1], 1, [[[h], 1], 1], 1, [[[...]|...], 1], 1] ;
false.

我怎样才能使它正确?

4

2 回答 2

4

这是您可以采取的另一种方式...基于并定义: if_/3 (=)/3 list_hxys/2

list_hxys([E|Es], [h|Xs]) :-
   list_hxys_prev(Es, Xs, E).

list_hxys_prev([], [], _).
list_hxys_prev([E|Es], [X|Xs], E0) :-
   if_(E = E0, X = y, X = x),
   list_hxys_prev(Es, Xs, E).

使用 SICStus Prolog 4.3.2 的一些示例查询:

| ?- list_hxys([a,a,b,b], Xs).         % (query given by the OP)
Xs = [h,y,x,y] ? ;                     % expected answer
no
| ?- list_hxys(As, [h,y,x,y]).         % works the "other" way around, too
As = [_A,_A,_B,_B],
prolog:dif(_B,_A) ? ;                  % answer with residual goal dif/2
no
于 2016-05-23T18:33:25.937 回答
0

让我们分解一下:

% Two elements being read are the same -> add y
control([H,H|T],[y|R]) :- control([H|T],R).

% Two elements being read are not the same -> add x
control([H1,H2|T],[x|R]) :- H1 \== H2, control([H2|T],R).

在这两个子句中,我们使用除第一个检查元素之外的所有元素进行递归调用,并分别在结果中添加“x”或“y”。

现在由您来定义基本情况,但是请注意,根据输入列表的元素数量是偶数还是不均匀,将需要两种基本情况:一种用于具有单个元素的列表,另一种用于空列表。

于 2016-05-22T20:31:34.967 回答