Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Prolog 在列表序言中列出给定数量的元素_Prolog - Fatal编程技术网

Prolog 在列表序言中列出给定数量的元素

Prolog 在列表序言中列出给定数量的元素,prolog,Prolog,我试图列出我存储在列表中的给定数量的元素,我的代码如下 埃尔佩森,名单:-芬达拉,后代人,A,名单 当我在prolog中输入下面的代码时,我得到了与我的查询匹配的所有元素 埃尔詹姆斯,X 我试图实现的是让prolog列出给定数量的元素,例如 埃尔詹姆斯,3岁 Prolog最多只能从列表中返回3个元素。我做了一些研究,发现我可以使用findnsols而不是findall运算符,但我找不到一种实用的方法在我的代码中实现它。好吧,显而易见的方法是这样说: er(P,N,L) :- findnsol

我试图列出我存储在列表中的给定数量的元素,我的代码如下

埃尔佩森,名单:-芬达拉,后代人,A,名单

当我在prolog中输入下面的代码时,我得到了与我的查询匹配的所有元素

埃尔詹姆斯,X

我试图实现的是让prolog列出给定数量的元素,例如

埃尔詹姆斯,3岁


Prolog最多只能从列表中返回3个元素。我做了一些研究,发现我可以使用findnsols而不是findall运算符,但我找不到一种实用的方法在我的代码中实现它。

好吧,显而易见的方法是这样说:

er(P,N,L) :-
  findnsols(N,A,descendant(P,A),L)
  .
er(P,L) :-
  var(L),
  findall(A,descendant(P,A),L)
  .
er(P,L) :-
  nonvar(L),
  length(L,N),
  findnsols(N,A,descendant(P,A),L)
  .
er(james,L).
er(james,[A,B,C]).
但你似乎不想这么做。你可能会考虑这样的事情:

er(P,N,L) :-
  findnsols(N,A,descendant(P,A),L)
  .
er(P,L) :-
  var(L),
  findall(A,descendant(P,A),L)
  .
er(P,L) :-
  nonvar(L),
  length(L,N),
  findnsols(N,A,descendant(P,A),L)
  .
er(james,L).
er(james,[A,B,C]).
如果您想要恢复所有解决方案,只需如下调用:

er(P,N,L) :-
  findnsols(N,A,descendant(P,A),L)
  .
er(P,L) :-
  var(L),
  findall(A,descendant(P,A),L)
  .
er(P,L) :-
  nonvar(L),
  length(L,N),
  findnsols(N,A,descendant(P,A),L)
  .
er(james,L).
er(james,[A,B,C]).
如果你想限制一些事情,比如:

er(P,N,L) :-
  findnsols(N,A,descendant(P,A),L)
  .
er(P,L) :-
  var(L),
  findall(A,descendant(P,A),L)
  .
er(P,L) :-
  nonvar(L),
  length(L,N),
  findnsols(N,A,descendant(P,A),L)
  .
er(james,L).
er(james,[A,B,C]).
或者,由于长度/2可以生成:

length(5,L) , er(james,L).

findnsols3,A,后代人,A,列表应该可以工作。请解释你的问题…findnsols对我来说不是最优的,因为它需要两个以上的元素来保持它在erX,Y,findnsols的问题是我必须在查询中包含一个精确的数字,而不是在程序本身中键入它。说findnsolsNth,一个,后代人,一个,列表。n可以是0到999之间的任何数字。FindNSolsOntn等允许“动态”更改返回的列表长度。但是这个高级功能似乎超出了您的需要。在调用findnsols之前,您将知道值Nth,不是吗?所以就用它吧