2017-10-06 18 views
1

所以,我在找的是基本上是这样的:如何找到列表中发现某个原子的第一次出现的列表?

findatom(A, L, NL), 
with inputs: 
A = -, %sought after atom 
L = [[1,2,3], [2,-,3], [1,2,3]] %list of lists 
and then it outputs: 
NL = [2,-,3] %the first list containing the sought after atom 

怎么可能呢?我试过这个:

/*Append something (dummy variable) with the first occurence of the 
sought after atom (L), then output everything after the found atom (L). */ 

     findatom(L, List, NewList) :- 
      append(_, [L|T], List), 
      NewList = [L|T]. 

这只适用于存在原子列表而不是列表列表的情况。我怎样才能扩展它以使其适用于列表清单?

+0

虽然追加可以用最惊人的方式使用,但我不完全清楚为什么你认为使用它? –

回答

1

让我们用文字做这个:findatom(A, L, NL)找到列表NLL这样A就在里面。让我们用Prolog谓词替换那些单词:findatom(A, L, NL)找到L的member NL,使得ANL的成员。

findatom(A, L, NL) :- 
    member(NL, L),  % find an item NL in L 
    memberchk(A, NL). % that contains A 

这里使用memberchk的好处在于,它是确定性的,所以你不必担心会多个错误的解决方案。

相关问题