prolog 搜索列表
我正在尝试比较这些列表。给定函数(List1,List2)并且List1具有长度N并且List 2具有长度M并且N>M。
我想检查 List2 的任何排列是否恰好是 List1 的前 M 个字符。
例如,
predicate([a,c,b,d,e],[a,b,c,d]).
应该为真,也
predicate([a,c,b,e,d],[a,b,c,d]).
应该为假。
谢谢。
I am trying to compare the lists. Given function(List1,List2) and List1 has length N and List 2 has length M and N>M.
I want to check if any permutation of List2 happens to be the first M characters of List1.
eg,
predicate([a,c,b,d,e],[a,b,c,d]).
should be true and
predicate([a,c,b,e,d],[a,b,c,d]).
should be false.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在描述列表之间的关系时,DCG 在这种情况下很方便:
示例案例:
As often when describing relations between lists, DCGs are convenient in this case:
Sample cases:
使用
permutation/2
和prefix/2
谓词,您可以编写如下内容:作为旁注并引用 swi-prolog 手册 :
因此,我会注意不要使用太长的第二个列表来调用
has_prefix_perm/2
,特别是如果它恰好不是前缀模排列,因为所有情况都将被测试。另一种方法是测试 List1 项目是否是 List2 的成员,直到 List2 为空,这样您就知道存在排列:
像这样写,我不会在非地面列表上使用它,但看到您的OP我没有进一步搜索...
另一种方法是检查 List1 减少到 List2 的长度是否是 List2 的排列:
另一种方法是...我想有很多方法可以做到这一点,只需选择一个不是的方法可怕的复杂性和适合性你的风格! :)
我个人会选择最后一个。
Using the
permutation/2
andprefix/2
predicates you could write something such as :As a side note and to quote swi-prolog manual :
So I'd take care not to call
has_prefix_perm/2
with a too lengthy second list, especially if it happens not to be a prefix modulo permutation, since all the cases will be tested.Another way would be to test if List1 items are members of List2 until List2 is empty, that way you know that a permutation exists :
Written like that, I wouldn't use it on non ground lists, but seeing your OP I didn't search further...
Another way would be to check if List1 reduced to the length of List2 is a permutation of List2 :
Another way would be to... I guess there are lots of ways to do that, just pick one that isn't horrible complexity wise and fits your style ! :)
I'd go with the last one personally.
这是另一个 DCG 解决方案。
出处:Prolog 时刻,展示 0
Here is another DCG solution.
Attribution: Moments of Prolog, exhibit 0