Search code examples
prologclpfd

Simple nth1 predicate in Prolog


With SWI Prolog, there's a predicate that finds the nth item in a list called nth1. I want to implement my own version of the predicate but SWI's is so complicated if you look at the listing(nth1) code. Is there a simpler way of doing it?

Thank you :).


Solution

  • The SWI code is a bit complex because the predicate can be used to generate from a variable index:

    ?- nth1(Idx,[a,b,c],X).
    Idx = 1,
    X = a ;
    Idx = 2,
    X = b ;
    Idx = 3,
    X = c ;
    false.
    

    If you don't want that behavior, nth1/3 can be implemented easily in terms of nth0:

    nth1(Idx,List,X) :-
        Idx0 is Idx-1,
        nth0(Idx0,List,X).
    

    Edit: it's also possible to do without nth0 in just a few lines of code:

    nth1(1,[X|_],X) :- !.
    nth1(Idx,[_|List],X) :-
        Idx > 1,
        Idx1 is Idx-1,
        nth1(Idx1,List,X).