Prolog如何将列表中的前3个元素存储到另一个列表中
我尝试过这样的事情: 说path = [[1,2],[2,3],[3,4],[5,6]]
first_three(N,[H|T],[H|_]):- not(N=0),N is N-1, first_three(N,T,L).
然后我调用first_third(3, path, Y) 但它返回no。
I tried something like this:
said path = [[1,2],[2,3],[3,4],[5,6]]
first_three(N,[H|T],[H|_]):- not(N=0),N is N-1, first_three(N,T,L).
then I call first_three(3, path, Y) but it return no.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要添加一个基本情况(当 N = 0 时)。并且还需要实例化一个新的fresh变量来给N的前驱赋值,最后还需要返回递归的结果(子句头部的[H|L]):
当然,你也可以只需编写如下内容:
并调用它:
You need to add a base case (when N = 0). And you also need to instantiate a new fresh variable to assign the predecesor of N, and finally you also need to return the result of the recursion (the [H|L] in the head of the clasuse):
Of course, you can also just write something like this:
and call it:
首先,
N is N - 1
不可能成功 -N
不是命令式编程语言意义上的变量,因此您不会在其中存储值,它只能被赋值一次,可以这么说 - 所以你可能想引入一个新变量并调用类似N1 is N - 1
的东西,然后在中使用N1
对first_third
的递归调用。然后,该递归调用的最后一个参数不知从何而来,因此您可能也需要注意它。作为最后一个建议,尝试将谓词分成两个子句:第一个子句管理基本情况,其中N
为0
,第二个子句管理重要情况,构建在另一个之上。哦,由于
N
是一个可变数量,我建议为您的谓词使用不同的名称,而不是误导性的first_third
。First of all,
N is N - 1
can't possibly succeed -N
is not a variable in the imperative programming language sense, so you don't store values in it, it can be assigned only once, so to speak - so you may want to introduce a new variable and call something likeN1 is N - 1
, and subsequently useN1
in the recursive call tofirst_three
. Then, the last argument to that recursive call comes out of nowhere, so you may need to pay attention to it too. As a last suggestion, try to split the predicate in two clauses: the first to manage the elementary basic case whereN
is0
, the second to manage the meaty cases, building on top of the other.Oh, and since
N
is a variable quantity, I would suggest to use a different name rather than the misleadingfirst_three
for your predicate.