查找相邻成员 [英] Find adjacent members

查看:48
本文介绍了查找相邻成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须找出列表中的两个成员是否相邻.限制是使用 append/3 谓词.到目前为止,我已经完成了下面的工作,如果它是真的,它就可以工作,否则我得不到答案,就像它永远运行一样.

相邻(X,Y,L):-追加(L1,[X,Y],T1),追加(T1,T2,L).

解决方案

要查看您的程序是否会循环,只需考虑以下 :

<预>相邻(X,Y,L): -追加(L1,[X,Y],T1),追加(T1,T2,L).

如果这个程序会循环,那么原来的程序也会循环.它可能会成功,但它仍然会循环.

在您的第一个目标中,L1T1 都是未实例化的变量 - 这很容易看到,因为在此片段中的其他任何地方都没有使用它们.因此,无论XYL 是什么,该程序将总是循环.要解决此问题,您必须修改可见部分中的某些内容.

一种可能性是交换两个目标.但还有更简单的方法:

相邻(X,Y,L) :-追加(_,[X,Y|_],L)

但是请注意,这并不能确保 L 确实是一个格式良好的列表.事实上,adjacent(1,2,[1,2|nonlist]) 成功了.如果它应该是一个列表:

相邻(X,Y,L) :-追加(_,[X,Y|R],L),追加(R,[],R).

参见了解更多.

I have to find if two members of a list are adjacent. The restriction is to use the append/3 predicate. So far I've done the below, it works if it's true, otherwise I get no answer, it's like it runs eternally.

adjacent(X,Y,L):-
   append(L1,[X,Y],T1),append(T1,T2,L).

解决方案

To see that your program will loop, it suffices to consider the following :

    adjacent(X,Y,L):-
       append(L1,[X,Y],T1), false,
       append(T1,T2,L).

If this program will loop, then the original program will loop too. It might succeed, but still it will loop.

In your first goal both L1 and T1 are uninstantiated variables - that's easy to see, because they are not used anywhere else in this fragment. As a consequence, this program will always loop, no matter what X, Y or L might be. To fix this, you have to modify something in the visible part.

One possibility would be to exchange the two goals. But there is an even easier way out:

adjacent(X,Y,L) :-
   append(_,[X,Y|_],L)

Note however, that this does not ensure that L is really a well formed list. In fact, adjacent(1,2,[1,2|nonlist]) succeeds. In case it should be a list:

adjacent(X,Y,L) :-
   append(_,[X,Y|R],L),
   append(R,[],R).

See for more.

这篇关于查找相邻成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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