-1

我需要编写一个谓词 f(L,R) 当且仅当 L 是包含 R 中所有非列表项的列表时才成功。例如:

f(L,[1,2,3,[4,5,6],[[7,8,9]],[]]).

应该给:

L = [1,2,3,4,5,6,7,8,9]

我写了一个谓词,它给出了以下结果:

L = [1,2,3,4,5,6,7,8,9,[]]

结果中不应出现空列表。我的谓词如下:

f([],[]).
f(V,[H|T]):-  H = [_|_] -> append(L,R,V),
              f(L,H),  f(R,T),!;
              V = [H1|T1], H1=H, f(T1,T).

我有两个疑问。首先,结果中不应出现空列表。另外我不知道为什么如果我不切(!)它不起作用。事实上,如果我不删减它会给我上面的结果,但如果我要求另一个结果,它会永远循环。我真的不明白为什么这应该循环。

4

1 回答 1

1

To remove the empty list, handle that case (discard it).

About the loop: I think the cause could be that you're calling append(L,R,V) with all arguments not instantiated: move append after the recursive calls.

Finally, maybe you don't use rightly the 'if then else' construct: I've indented using the usual SWI-Prolog source style, using indentation to highlight 'sequential' calls

f([], []).
f(V, [H|T]) :-
    (   H = []      % if H = []
    ->  f(V, T)     %  then discard
    ;   H = [_|_]   % else if H is list
    ->  f(L,H),     %  flat head
        f(R,T),     %  ...
        append(L,R,V)
    ;   V = [H|T1], % else 
        f(T1,T)     %  ...
    ).
于 2012-11-23T22:55:14.537 回答