list 通过列表进行序言迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30800407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:08:05  来源:igfitidea点击:

Prolog-iterating through list

listprologiterationhead

提问by Dago

Let's say i have list Xs = [a,b,c].Now i want to iterate through all elements and call another function for this elements. My question is: how to do this using head and tail? I would be grateful for help.

假设我有列表Xs = [a,b,c].现在我想遍历所有元素并为此元素调用另一个函数。我的问题是:如何使用头部和尾部来做到这一点?我将不胜感激。

回答by dasblinkenlight

Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this:

通常,您不会在 Prolog 中进行迭代。相反,您使用一对递归子句编写规则,如下所示:

 dosomething([]).
 dosomething([H|T]) :- process(H), dosomething(T).

The first clause processes the base case, when the list []is empty. In this case, there is nothing to do, so the body of the rule is empty as well.

当列表[]为空时,第一个子句处理基本情况。在这种情况下,没有什么可做的,所以规则的主体也是空的。

The second clause processes the case when your list has at least one element. Syntax [H|T]unifies with your list in such a way that Hbecomes the head of the list, and Tbecomes its tail. For example, if you process dosomething([a,b,c]), Hbecomes a, and Tbecomes [b,c].

当您的列表至少有一个元素时,第二个子句处理这种情况。语法[H|T]以这样的方式与您的列表统一,H成为列表的头部,并T成为其尾部。例如,如果您处理dosomething([a,b,c])H变成aT变成[b,c]

The body of this rule has two parts. The first part operates on the head, calling processon it. This is the rule that you want executed for each element of the list. The second part invokes dosomethingrule recursively on the tail of the list. When the tail list is not empty, the second clause of dosomethingwould unify with the shorter list to continue processing. When the tail list is empty, the first clause would unify, thus ending the processing.

该规则的主体有两个部分。第一部分作用于头部,呼唤process它。这是您要为列表的每个元素执行的规则。第二部分dosomething在列表的尾部递归调用规则。当尾列表不为空时,第二个子句dosomething将与较短的列表统一继续处理。当尾表为空时,第一个子句将统一,从而结束处理。