且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Prolog- 返回元素的索引

更新时间:2023-11-26 08:05:40

您可以使用内置谓词 nth1/3 直接使用它来实现您想要的.

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

[在 OP 改写问题后编辑]

[edited after OP rephrased question]

第一个子句枚举列表中项目的索引,第二个子句只是将每个 OP 要求的 Index 与 -1 统一起来.

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