简体   繁体   English

从Prolog中的嵌套列表中取出第一个元素

[英]Take out first elements from nested lists in Prolog

Problem: I need to transform this list: [[1,2],[3,4],[5,6]] to [1,3,5] , by taking only first items from each sub-list in first list and creating new list with all of them. 问题:我需要通过仅从第一个列表中的每个子列表中获取第一个项目来将这个列表: [[1,2],[3,4],[5,6]][1,3,5]并与他们一起创建新列表。 Language is SWI-Prolog . 语言是SWI-Prolog

My solution : To do this, I wrote this code: 我的解决方案 :为此,我编写了以下代码:

getFirstItems([], Result).
getFirstItems([H|T], Result) :-
    [H2|T2] = H, 
    append(Result,H2,Result2),
    getFirstItems(T, Result2).

Issue : But this fails to infinite recursion when tail always equals to [[5,6]] 问题 :但这在尾部始终等于[[5,6]]时无法无限递归

Question : how to solve this issue and solve this problem correctly? 问题 :如何解决此问题并正确解决此问题?

You are complicating things too much. 您使事情变得过于复杂。 You need to reason with a declarative mindset, and thus implement what the relationships between the list of lists and the list of first elements are . 您需要以声明性的思维方式进行推理,从而实现列表列表和第一个元素列表之间的关系

Here is a solution: 这是一个解决方案:

first_items([], []).
first_items([[H|_]|T], [H|T2]) :-
    first_items(T, T2).

Indeed, the only two things we need to state to describe that relationship are: 确实,我们需要说明的唯一两件事是:

  • If the list of lists is empty, then so is the list of first elements. 如果列表列表为空,则第一个元素的列表也为空。
  • a first element H is in the list of first elements, followed by the first elements ( T2 ) of the rest of the list of lists ( T ). 第一个元素H在第一个元素的列表中,后面是列表的其余列表( T )中的第一个元素( T2 )。

Example queries: 查询示例:

?- first_items([[1,2],[3,4],[5,6]], Z).
Z = [1, 3, 5].

?- first_items(L, [1,3,4]).
L = [[1|_22058], [3|_22070], [4|_22082]].

?- first_items(L, Z).
L = Z, Z = [] ;
L = [[_22048|_22050]],
Z = [_22048] ;
L = [[_22048|_22050], [_22066|_22068]],
Z = [_22048, _22066]
…

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM