简体   繁体   中英

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. then it will unify Y with X.

Still confused about the code that 'unifies' these elements

The fail after the cut ! 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. The |_ part allows the list to have more elements (it unifies the tail with an anonymous variable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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