prolognth-element

How to find nth element of list and have answer be in R PROLOG


Very new to prolog. I am trying to create a simple recursive rule to find nth element on the list. For example if I have a list of strings or numbers I want to be able to use the query

?- findme([dog, cat , bird], 1, R). 
R = dog 
?- findme([9,8,7,6,5], 3,R). 
R= 7
?- findme([mouse,cheese,cat,milk], 5, R).
R = false

I wish not to use the builtin Nth0, nor have R such that R is n -1


Solution

  • Here is my implementation:

    find([],N,false):-N>0.    
    find([H|_],1,H).   
    find([_|T],N,R) :- N1 is N-1, find(T,N1,R).
    

    Some examples:

    ?- find([dog, cat , bird], 1, R).
    R = dog ;
    false.
    
    ?- find([mouse,cheese,cat,milk], 5, R).
    R = false.
    
    ?- find([9,8,7,6,5], 3,R).
    R = 7 ;
    false.