Mohammad Arshad
Mohammad Arshad

Reputation: 25

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

Upvotes: 0

Views: 1091

Answers (2)

Wasi Ahmad
Wasi Ahmad

Reputation: 37771

The following is giving expected output.

find([],N) :- write("There is no such element in the list"), nl.    
find([Element|List],1) :- write("The element is ", Element), nl.   
find([Element|List],N) :- N1 = N-1, find(List,N1).

Output :

find([1,2,3,4],3)
The element is 3
Yes

find([1,2,3,4],0)
There is no such element in the list
Yes

find([1,2,3,4],5)
There is no such element in the list
Yes

find([1,2,4,3],4)
The element is 3
Yes

Update

find([],N,false) :- N>0.
find([Element|List],1,Element).   
find([Element|List],N,R) :- N1 = N-1, find(List,N1,R).

Upvotes: 0

coder
coder

Reputation: 12992

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.

Upvotes: 1

Related Questions