Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Prolog-处理列表列表和其中一个子列表中的元素_Prolog_Logic_Nested Lists_List Manipulation - Fatal编程技术网

Prolog-处理列表列表和其中一个子列表中的元素

Prolog-处理列表列表和其中一个子列表中的元素,prolog,logic,nested-lists,list-manipulation,Prolog,Logic,Nested Lists,List Manipulation,我知道这里的一些问题与这个问题类似,但我缺乏经验,不知道如何使用它们,如何将解决方案转化为我的问题/ 我有一个列表,里面有列表,比如: given_elem_finds_pos( [[H|T]| R], Element, Ind):- member(Element, [H|T]), Ind1 is Ind + 1, given_elem_finds_pos(R, Element, Ind1). [[5]、[4,7]、[1,2,7]、[2,6,7]、[2,4,6,7]、[2,4,7]、[9,8]

我知道这里的一些问题与这个问题类似,但我缺乏经验,不知道如何使用它们,如何将解决方案转化为我的问题/

我有一个列表,里面有列表,比如:

given_elem_finds_pos( [[H|T]| R], Element, Ind):-
member(Element, [H|T]),
Ind1 is Ind + 1,
given_elem_finds_pos(R, Element, Ind1).
[[5]、[4,7]、[1,2,7]、[2,6,7]、[2,4,6,7]、[2,4,7]、[9,8]、[3]、[1]

我需要知道,例如,数字3的索引。我需要知道的号码只会在列表列表中出现一次,这是调用函数的前一个条件。我需要的索引是,对于数字3,索引9(从1开始)。我有一个函数草案:

given_elem_finds_pos(ListOfLists, Element, Pos):-
    nth1(Pos, ListOfLists, [Element|_]).
但它仅在元素是子列表的头时返回Pos。我需要知道如何获取索引,例如数字8

然后我做了这个:

given_elem_finds_pos( [[H|T]| R], Element, Ind):-
member(Element, [H|T]),
Ind1 is Ind + 1,
given_elem_finds_pos(R, Element, Ind1).

但同样的,没有成功。。有人能帮忙吗?非常感谢你

您的第二种方法正朝着正确的方向发展。想想你想描述什么:如果
Element
[H | T]
的一个元素,你想停止,因此,这里不需要递归调用。此外,您希望返回当前索引,因此需要一个额外的参数(一个用于计数器,一个用于最终索引)。如果
元素
不是列表中的元素,则需要递归子句。下面是一个子句,用于表示它是一个元素的情况

 given_elem_finds_pos( [List| R], Element, Solution,Solution):-
        member(Element, List).
由于必须添加额外的参数,因此需要一个调用扩展谓词的额外谓词:

given_elem_finds_pos(ListOfLists, Element, Ind):-
        given_elem_finds_pos(ListOfLists, Element,0, Solution).

现在,您只需为给定的\u elem\u finds\u pos/4再编写一个子句,对于“it's not a element”情况,这是一个递归子句。如果您在撰写本条款时遇到困难,请询问。

谢谢您的快速回复!我正在研究另一个子句,并试图找出你做了什么,所以我不能说一切都完成了,但告诉我:在上一次迭代中,或者上次调用“elem\u finds\u pos/4”时,Prolog最终得到了一个不断增加1的索引,对吗?或者你不在自己身上做?因为如果你这样做了,那么最终的值不是和解决方案相同吗?是的,你是对的,计数器在增加,如果找到搜索的子列表,计数器等于索引。这就是为什么你需要额外的理由。我的代码中的stop子句以
gived_elem_finds_pos([List | R],元素,解决方案,解决方案)]-
开头,用当前计数器实例化解决方案索引。