简体   繁体   English

Prolog对齐谓词

[英]Prolog A predicate for alignment

By alignment I mean that the predicate takes in two lists, well three with the alignment list. 对齐是指谓词包含两个列表,其中三个包含对齐列表。 And then check that every item in the alignment list is indeed an element in both the other lits. 然后检查对齐列表中的每个项目的确是其他两个照明灯中的一个元素。 And there is a requirement about order, so that rules out just checking that every item in the alignment list is a member of both the other input lits. 并且有关于顺序的要求,以便排除仅检查对齐列表中的每个项目是否都是其他两个输入灯的成员的可能性。 If I just check for member, a valid alignment would also be valid when reversed. 如果我只是检查成员,则当反向时有效的对齐方式也将有效。 Which of course is wrong. 当然哪个是错误的。

Example:
?- mxAli([4,2,9,8],[1,9,5,2,3,8],A).
A=[2,8] or A=[9,8]

8,2 and 8,9 is not valid here. 8,2和8,9在这里无效。

At once when I think about how to actually check the order my head goes back too imperative language programming. 当我想到如何实际检查顺序时,我的头又回到了命令式语言编程的高度。 Any input is much appreciated. 非常感谢任何输入。 But don't give the answer straight out, I want hints on what I should read about. 但不要直接给出答案,我想提示我应该读些什么。 (I need to say this, because I get so good help at this site that it's close too cheating if I don't point this out). (我必须这样说,因为在此站点上我获得了很好的帮助,以至于如果我不指出这一点的话,它就太骗人了)。

My idea is that I , or prolog, needs to continue its search after the index of it's current element. 我的想法是,我或prolog需要在其当前元素的索引之后继续搜索。 That would make the reverse alignment not valid? 那会使反向对齐无效吗?

Edit: It would have to continue the search, after the current element's index in both the lists. 编辑:在两个列表中当前元素的索引之后,都必须继续搜索。 As in the example above, when it finds the 2, it starts the search for the next element at index 2 and at index 5. (First element being 1) 如上例所示,当找到2时,它开始在索引2和索引5处搜索下一个元素。(第一个元素为1)

A naive way to check alignment would be to use append/3 , ie something like: 一种简单的检查对齐方式是使用append/3 ,即:

append(_, [El | T1], L1),
append(_, [El | T2], L2),
...

where L1 and L2 are the given lists, and El is an element that they must share. 其中L1L2是给定的列表,而El是它们必须共享的元素。 Later you can check if T1 and T2 align. 以后您可以检查T1T2对齐。

What follows is the complete solution: 以下是完整的解决方案:

align(L1, L2, [El | T]) :-
    append(_, [El | T1], L1),
    append(_, [El | T2], L2),
    align(T1, T2, T).

align(_L1, _L2, []).

% Test, executed at consult time
:- align([4,2,9,8], [1,9,5,2,3,8], Alignment), writeln(Alignment), fail; true.

The test prints out: 测试输出:

[2, 8]
[2]
[9, 8]
[9]
[8]
[]

The key is not thinking algorithmically too much but going through cases where the predicate should be true. 关键不是算法上的思考过多,而是要研究谓词为真的情况。

Here I would consider the cases that the alignment list (3rd argument) is empty and that it is not empty. 在这里,我将考虑对齐列表(第三个参数)为空且不为空的情况。 For the nonempty case describe what has to hold for the first element of the output list and use recursion for the rest of the list. 对于非空的情况,请描述输出列表的第一个元素必须保留的内容,并对其余列表使用递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM