简体   繁体   English

SWI-Prolog规则

[英]SWI-Prolog Rule

My rule is supposed to unify the first parameter with the third element in the list. 我的规则应该是将第一个参数与列表中的第三个元素统一起来。 The list is the second parameter in the rule. 该列表是规则中的第二个参数。 If there is no third element, this should fail. 如果没有第三个元素,则应该失败。

After many examples and confusion i have created this rule. 经过许多例子和混乱,我创造了这个规则。

third(X,[_|T]):-
    [_,Y] = T,!,fail,
    (Y,X).

So my understanding, which i believe is incorrect, it will set Y to the third element of the list T, since T is the tail part of the initial list. 所以我的理解,我认为是不正确的,它会将Y设置为列表T的第三个元素,因为T是初始列表的尾部。 then it will unify Y with X. 然后它会将Y与X统一起来。

Still confused about the code that 'unifies' these elements 仍然对“统一”这些元素的代码感到困惑

The fail after the cut ! 切后fail ! assures that your procedure will never succeed, because you are commiting choices with the cut and then failing. 确保你的程序永远不会成功,因为你正在选择削减然后失败。

You can access the third element of the list the way you try to do it only if the list has exactly three elements: you skip the first element in the head of the procedure, then take the second element from the tail. 只有当列表中只包含三个元素时,才可以按照尝试的方式访问列表的第三个元素:跳过过程头部的第一个元素,然后从尾部获取第二个元素。

third(X,[_|T]):-
    [_,X] = T.

Note that this procedure will fail if the list does not have exactly three elements. 请注意,如果列表中没有正好三个元素,则此过程将失败。

However, it is more straightforward to access directly the third element in the head of the procedure, eg: 但是,直接访问过程头部的第三个元素更为直接,例如:

third(X, [_, _, X|_]).

This will unify X with the third element of the list from the second argument. 这将使X与第二个参数的列表的第三个元素统一起来。 The |_ part allows the list to have more elements (it unifies the tail with an anonymous variable). |_部分允许列表包含更多元素(它使用匿名变量统一尾部)。

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

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