Prolog如何将列表中的前3个元素存储到另一个列表中

发布于 2024-12-09 14:29:20 字数 191 浏览 0 评论 0原文

我尝试过这样的事情: 说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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸里的那抹悲凉 2024-12-16 14:29:20

您需要添加一个基本情况(当 N = 0 时)。并且还需要实例化一个新的fresh变量来给N的前驱赋值,最后还需要返回递归的结果(子句头部的[H|L]):

first_three(0,_,[).
first_three(N,[H|T],[H|L]):- 
  N\=0,
  N1 is N-1, 
  first_three(N,T,L).

当然,你也可以只需编写如下内容:

first_three([One,Two, Three|_], [One,Two, Three]).

并调用它:

first_three(Path, Y).

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):

first_three(0,_,[).
first_three(N,[H|T],[H|L]):- 
  N\=0,
  N1 is N-1, 
  first_three(N,T,L).

Of course, you can also just write something like this:

first_three([One,Two, Three|_], [One,Two, Three]).

and call it:

first_three(Path, Y).
梦里寻她 2024-12-16 14:29:20

首先,N is N - 1 不可能成功 - N 不是命令式编程语言意义上的变量,因此您不会在其中存储值,它只能被赋值一次,可以这么说 - 所以你可能想引入一个新变量并调用类似 N1 is N - 1 的东西,然后在中使用 N1first_third 的递归调用。然后,该递归调用的最后一个参数不知从何而来,因此您可能也需要注意它。作为最后一个建议,尝试将谓词分成两个子句:第一个子句管理基本情况,其中 N0,第二个子句管理重要情况,构建在另一个之上。

哦,由于 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 like N1 is N - 1, and subsequently use N1 in the recursive call to first_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 where N is 0, 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 misleading first_three for your predicate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文