问题描述
我得到了一个问题:
到目前为止,我有这个:
So far I have this:
ordered([]).
ordered([N, M|Ns]):-
append(M, Ns, Tail),
ordered(Tail),
N =< M.
但是在每个列表上都会失败.
But it fails on every list.
我已经推断出失败的原因是因为它到达列表中的结尾数字,然后尝试将该数字与一个空列表进行比较.显然,这失败了,因为您无法将整数与空列表进行比较.即使您可以并且说它返回0
以获得一个空列表,它仍将返回false,因为该数字将大于0
,而不是小于.
I have deduced that the reason it fails is because it reaches the end number in the list then tries to compare that number against an empty list. Obviously this fails because you can't compare an integer to an empty list. Even if you could and it, say, returned 0
for an empty list, it would still return false as the number would be greater than 0
, not less than.
我找不到解决方案...有什么想法吗?谢谢,乔恩.
I can't find a solution... Any ideas? Thanks, Jon.
因此,一些经过稍微修改的代码:
So, some slightly amended code:
ordered([]).
ordered([N]):-
N >= 0.
ordered([N, M|Ns]):-
append(M, Ns, Tail),
ordered(Tail),
N =< M.
这现在适用于ordered([1])
,但是较大的列表仍然无法正确运行.
This now works for ordered([1])
, but bigger lists still don't run correctly.
我是否应该在定义中包含类似ordered([N, M|Ns])
的内容?
Should I include something like ordered([N, M|Ns])
in the definition?
推荐答案
最后,它非常容易修复.
Well that, in the end, was rediculously easy to fix.
这是正确的代码.
ordered([]).
ordered([N, M|Ns]):-
append([M], Ns, Tail),
ordered(Tail),
N =< M.
ordered([M]).
已排序([M]).如上所述处理单元素列表.
ordered([M]). deals with the single-element list as described above.
我的问题的真正根源不在追加函数中的M周围包含[].
The real root of my problem was not including [] around the M in the append function.
关于授予正确答案的菜谱是什么?你们俩都提供了很大帮助.
Whats the ettiquette regarding awarding the correct answer? You've both helped muchly.
乔恩
这篇关于到达序言中的列表结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!