Prolog-如何使尾巴不为空 [英] Prolog - How do I get the tail to not be null
问题描述
我有以下问题:
I have the following problem:
定义一个谓词sorted(LL)
,当列表LL
时满足
包含其他列表,这些列表按长度递增的顺序排序.
例如:
Define a predicate sorted(LL)
, that is satisfied when the list LL
contains other lists that are sorted in order of increasing length.
For example:
?- sorted([[],[1],[1,1],[1,1,1]]) -> yes.
?- sorted([[],[1],[1,1]]) -> yes.
?- sorted([[1],[],[1,1],[1,1,1]]) -> no.
到目前为止,我有这段代码:
And I have this code so far:
% shorter/2
shorter([],_).
shorter([_|T1], [_|T2]) :- shorter(T1,T2).
% sorted/1
sorted([]).
sorted([_]).
sorted([L1,L2 | T]) :- shorter2(L1, L2), sorted([L2,T]).
问题包含在上面的行:sorted([L2,T])
.当列表列表中仅剩一个元素时,该调用将追加一个空列表[]
,因为short/2将失败.在下面的SWIPL跟踪中对此进行了描述.
The problem is contained in the above line: sorted([L2,T])
. When only one element is left in the list of lists, that call will append an empty list []
because of which shorter/2 will fail. It is depicted in the following SWIPL trace.
[trace] ?- sorted([[1],[2,3]]).
Call: (6) sorted([[1], [2, 3]]) ? creep
Call: (7) shorter2([1], [2, 3]) ? creep
Call: (8) shorter2([], [3]) ? creep
Exit: (8) shorter2([], [3]) ? creep
Exit: (7) shorter2([1], [2, 3]) ? creep
Call: (7) sorted([[2, 3], []]) ? creep <-- empty list appended
Call: (8) shorter2([2, 3], []) ? creep
Fail: (8) shorter2([2, 3], []) ? creep
Fail: (7) sorted([[2, 3], []]) ? creep
Fail: (6) sorted([[1], [2, 3]]) ? creep
推荐答案
您在sorted/1
谓词的最后一个子句中有两个错别字,应该是:
You have two typos in the last clause of the sorted/1
predicate, which should be:
sorted([L1,L2| T]) :- shorter(L1, L2), sorted([L2| T]).
这篇关于Prolog-如何使尾巴不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!