在包含元素的嵌套列表中打印列表 [英] Print a List inside a nested List that contains an element
问题描述
我有以下问题.
我得到一个listOfLists,一个值(行,列),我需要在包含该特定值的列表内获取列表,直到该值在该列表内的索引为止.
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,则仅当我的值是否在listOfList内(而不是我将要使用的列表)内时,才会为true或false.
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屋!