在包含元素的嵌套列表中打印一个列表 [英] Print a List inside a nested List that contains an element

查看:21
本文介绍了在包含元素的嵌套列表中打印一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.

我得到了一个 listOfLists,一个值 (row,col),我需要获取包含该特定值的列表中的列表,直到该列表中我的值的索引.

I'm given a listOfLists, a value (row,col) and I need to get the list inside a list that contains that certain value, up to my value's index inside that list.

例如

?- find_list([[(1,2),(1,3),(1,4)], [(2,2),(2,3),(2,4)]], (1,3), List2).
List2 = [(1,2),(1,3)].

我的问题是,如果我使用 member/2,我只会得到 true 或 false,因为我的值是否在 listOfList 内,而不是我需要使用的列表.

My problem is that if I use member/2 I will only get true or false for if my value is inside listOfList or not, and not the list that I will need to be working with.

如何获得包含我价值的列表?

How can I get that list that has my value inside it?

推荐答案

值是二维坐标有关系吗?您是否必须尊重它们的顺序,或者仅仅是列表中元素的顺序?我会假设后者.

Does it matter that the values are two-dimensional coordinates? Is there an ordering on them that you must respect, or is it simply the ordering of the elements in the list? I will assume the latter.

如果你想在某个时候拆分一个列表,标准的 append/3 谓词通常是要走的路.例如,假设我们想将列表 [a, b, c, d, e] 切割成包含 c 之前元素的前缀和包含之后元素的后缀c.这是如何完成的:

If you want to split a list at some point, the standard append/3 predicate is usually the way to go. For example, assume we want to cut the list [a, b, c, d, e] into a prefix containing the elements before c and a suffix containing the elements after c. Here is how that is done:

?- append(Prefix, [c | Suffix], [a, b, c, d, e]).
Prefix = [a, b],
Suffix = [d, e] ;
false.

这里 c 被排除在前缀之外,但这很容易解决:

Here c is excluded from the prefix, but that's easy to fix:

?- append(Prefix, [c | Suffix], [a, b, c, d, e]), append(Prefix, [c], UpToAndIncludingC).
Prefix = [a, b],
Suffix = [d, e],
UpToAndIncludingC = [a, b, c] ;
false.

我们可以给这个谓词起一个好听的名字:

We can give this predicate a nice name:

list_pivot_prefix(List, Pivot, Prefix) :-
    append(Prefix0, [Pivot | _Suffix], List),
    append(Prefix0, [Pivot], Prefix).

然后,您的 find_list/3 谓词只需在给定列表中找到此关系成立的所有列表:

And your find_list/3 predicate then simply finds all the lists in the given list of lists for which this relation holds:

find_list(Lists, Element, Prefix) :-
    member(List, Lists),
    list_pivot_prefix(List, Element, Prefix).

这是你的测试用例:

?- find_list([[(1,2),(1,3),(1,4)],[(2,2),(2,3),(2,4)]],(1,3),List2).
List2 = [ (1, 2), (1, 3)] ;
false.

这篇关于在包含元素的嵌套列表中打印一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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