如何在Prolog中打印有限数量的搜索

如何在Prolog中打印有限数量的搜索,prolog,Prolog,我有以下资料: item(one, 50, 40). item(two, 80, 70). item(three, 100, 55). item(four, 50, 45). item(five, 50, 40). item(six, 80, 70). item(seven, 100, 55). item(eight, 50, 45). 我使用以下命令显示所有值: findall((A,B,C), item(A,B,C), L). 但是,它会显示所有项目。如果有数百个这样的条目,这可能是一个

我有以下资料:

item(one, 50, 40).
item(two, 80, 70).
item(three, 100, 55).
item(four, 50, 45).
item(five, 50, 40).
item(six, 80, 70).
item(seven, 100, 55).
item(eight, 50, 45).
我使用以下命令显示所有值:

findall((A,B,C), item(A,B,C), L).
但是,它会显示所有项目。如果有数百个这样的条目,这可能是一个问题。如何显示有限数量的项目,如上述情况中的3项

我看到有一些关于这方面的帖子:但我无法将它们与我的问题相匹配

我正在尝试以下代码,但它没有选择列表的长度:

head(N):-
    findall((A,B,C), item(A,B,C),L),
    writeln(L),
    writeln("------ 1 ---------"),
    length(L, N),
    writeln(N),
    writeln("------ 2 ---------"),
    head2(L, N, 0).

head2(L, N, M):-
    M < N, 
    nth0(M, L, Item), 
    writeln(Item),
    X is M+1, 
    head2(L, N, X).

以下是我注意到的一件事:

head(N) :-
    findall((A,B,C), item(A,B,C),L),
    writeln(L),
    writeln("------ 1 ---------"),
    length(L, N),
    ...
考虑到基本的序言原则:只有当
findall/3
生成一个列表
L
并且
L
的长度正好是
N
时,这项工作才会成功。如果查询
head(3)
,并且
findall/3
生成长度不是3的列表,那么
length(L,N)
将失败,并且永远不会调用以下语句(
)。当然,由于在失败之前您有一个
writeln
,因此将执行
writeln
,显示您的结果

作为一般性意见,您应该尝试使用变量作为结果,而不是
writeln
语句
writeln
非常适合提示用户或跟踪代码的特定部分,但不适合生成可供以后使用的结果

另一种办法:

find_n_items(MaxCount, Items) :-
    findall((A,B,C), item(A,B,C), AllItems),
    length(AllItems, AllItemsCount),
    ItemsCount is min(AllItemsCount, MaxCount),
    length(Items, ItemsCount),  % Constrain the length of Items
    append(Items, _, AllItems). % Select ItemCount items from front of AllItems
在这里,我们将
Result
的长度限制为
findall/3
产生的最小值和请求的长度限制,并使用
append/3
AllResults
前面获取该数量的元素

:- dynamic limitcount/1.

maxbacktrack :-
    retract(limitcount(Current)),
    Current > 0,
    Next is Current-1,
    assert(limitcount(Next)).

firstN(N,Pred) :-
    retractall(limitcount(_)),
    asserta(limitcount(N)),
    Pred,
    maxbacktrack.

findN(N,Term,Pred,List) :-
    findall(Term,firstN(N,Pred),List).
例如:

?- findN(3,(A,B,C),item(A,B,C),L).
L = [ (one, 50, 40), (two, 80, 70), (three, 100, 55)].

很好的解决方案。谢谢
?- findN(3,(A,B,C),item(A,B,C),L).
L = [ (one, 50, 40), (two, 80, 70), (three, 100, 55)].