0

序言很新。我正在尝试创建一个简单的递归规则来查找列表中的第 n 个元素。例如,如果我有一个字符串或数字列表,我希望能够使用查询

?- 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

希望使用内置的 Nth0,也不希望 R 使 R 为 n -1

4

2 回答 2

1

这是我的实现:

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

一些例子:

?- 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.
于 2016-12-04T23:19:58.340 回答
0

以下给出了预期的输出。

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).

输出 :

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

更新

find([],N,false) :- N>0.
find([Element|List],1,Element).   
find([Element|List],N,R) :- N1 = N-1, find(List,N1,R).
于 2016-12-04T22:27:23.697 回答