Prolog- return index of an element

你。 提交于 2021-01-28 03:51:28

问题


I have been stumped for 3 hours now on this problem, I need to find the index of (A,B,C) where A is the index positions of B in list C (or -1 if not in the list). This is what I have so far,

indexof(A,0,[A|_]).
indexof(A,B,[_|C]):- Y is B-1, indexof(A,Y,C).

it gives the element at the index spot B, which is not what I want.

indexof(A,1,[1]).

should return A=0;A=-1.

I am horrible at Prolog, I've done Java my whole life, so please also provide explanations.


回答1:


You can use the builtin predicate nth1/3 which can be used directly to achieve what you want.

indexof(Index, Item, List):-
  nth1(Index, List, Item).
indexof(-1, _, _).

[edited after OP rephrased question]

The first clause enumerates the index of the item in the list, and the second clause just unifies Index with -1 per OP requirement.




回答2:


Try the following

indexof(A,0,[A|_]).
indexof(_,-1,[]).
indexof(A,D,[_|C]):- indexof(A,B,C), B > -1, D is B+1. 
indexof(A,D,[_|C]):- indexof(A,B,C), B = -1, D is B.

You needed to have the base case for [] and the increment logic for -1 as well



来源:https://stackoverflow.com/questions/9848401/prolog-return-index-of-an-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!