到达序言中的列表结尾 [英] Reaching end of list in prolog

查看:86
本文介绍了到达序言中的列表结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个问题:

定义谓词ordered/1,它检查整数列表是否正确地以升序排列.例如,目标ordered([1,3,7,11])应该成功,目标ordered([1,3,3,7])也应该成功,而目标ordered([1,7,3,9])应该失败.

Define a predicate ordered/1, which checks if a list of integers is correctly in ascending order. For example, the goal ordered([1,3,7,11]) should succeed, as should the goal ordered([1,3,3,7]), whereas the goal ordered([1,7,3,9]) should fail.

到目前为止,我有这个:

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.

乔恩

这篇关于到达序言中的列表结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆