Prolog- 返回元素的索引 [英] Prolog- return index of an element

查看:40
本文介绍了Prolog- 返回元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经被这个问题难住了 3 个小时,我需要找到 (A,B,C) 的索引,其中 AB 在列表 C 中(或者 -1 如果不在列表中).到目前为止,这是我所拥有的,

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

它给出了索引点B处的元素,这不是我想要的.

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

indexof(A,1,[1]).

应该返回A=0;A=-1.

我在 Prolog 上很糟糕,我一生都在做 Java,所以还请提供解释.

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

推荐答案

您可以使用内置谓词 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.

这篇关于Prolog- 返回元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆