且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在包含元素的嵌套列表中打印列表

更新时间:2023-01-12 17:55:18

值是二维坐标是否重要?您必须遵守它们上的顺序,还是仅仅是列表中元素的顺序?我会假设后者.

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.