0

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

2 Answers2

1

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.
coder
  • 12,313
  • 5
  • 30
  • 49
  • I guess instead of using `find([],1,false).`, you should use `find([],N,false).` because if you run for `find([], 3, R).` - it will not return R = false. correct me if i am wrong. – Wasi Ahmad Dec 04 '16 at 23:30
  • Yeah sure that's what I had done in the first place but I tested with find([],1,false). and worked so left it that way. Thanks very much!!! – coder Dec 04 '16 at 23:34
0

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).
Wasi Ahmad
  • 27,225
  • 29
  • 85
  • 140
  • I had looked at that example. However that does not print the R. For instance i run element_at([9,8,7,5,5], 3, R) it just gives me false – Mohammad Arshad Dec 04 '16 at 22:31
  • but you mentioned in your post that `findme([9,8,7,6,5], 3,R).` gives you `R = 7`. then what is the problem? actually i can't run code and check now in my laptop. – Wasi Ahmad Dec 04 '16 at 22:37
  • Actually @Wasi I would like to create a rule that will give me R = 7. I tried something similar your edit. Still gives me false. If I change things up it prints result for the n -1 value. For instance findme([9, 8. 7 ,5 ,5],3,R) I will get R = 8. Not what I am looking for. I want R = 7. – Mohammad Arshad Dec 04 '16 at 22:38
  • Thank you for the update. I had tried to work around that example too. I do not want to use the write function, and would like to have my query in the format of (list, Nth term, R) – Mohammad Arshad Dec 04 '16 at 23:14
  • @MohammadArshad i have added an update to my answer. hope that it will help you. – Wasi Ahmad Dec 04 '16 at 23:24