Prolog:您如何在两个列表之间进行迭代(嵌套循环)? [英] Prolog: How do you iterate between two lists (nest for-loop)?

查看:126
本文介绍了Prolog:您如何在两个列表之间进行迭代(嵌套循环)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我本周刚刚开始学习Prolog,所以我不确定在Prolog中是否可以进行for循环. 我在Prolog中有两个列表

I just started learning Prolog this week so I am not sure if for-loops are possible in Prolog. I have two lists in Prolog

stringList([hi,hello],[bye,later],X).

如何创建一个新的解决方案列表,每个列表只有一个元素?

How do I create a new solution list with one element per list?

因此输出应为:

X = [hi,bye]
X = [hi,later]
X = [hello,bye]
X = [hello,later]

推荐答案

使用Prolog的一个主要优点是,您可以委托这样的循环到Prolog 引擎.您不必显式地编写它们.

A major advantage when using Prolog is that you can delegate such loops to the Prolog engine. You do not have to write them explicitly.

例如,以您的情况为例,以这种方式思考问题: 持有(或应该持有)关于X的什么?

For example, in your case, think about the problem in this way: What holds (or should hold) about X?

我们可以说:

  1. X是一个包含两个元素的列表,例如[A,B].
  2. A是由第一个参数表示的列表的成员.
  3. B是第二个参数表示的列表的成员.
  1. X is a list with two elements, say [A,B].
  2. A is a member of the list that is denoted by the first argument.
  3. B is a member of the list that is denoted by the second argument.

所以,在Prolog中:

So, in Prolog:


one_from_each(As, Bs, [A,B]) :-
    member(A, As),
    member(B, Bs).

示例查询:


?- one_from_each([hi,hello],[bye,later], X).
X = [hi, bye] ;
X = [hi, later] ;
X = [hello, bye] ;
X = [hello, later].

它也可以在其他方向上起作用:


?- one_from_each(As, Bs, [hi,bye]).
As = [hi|_4656],
Bs = [bye|_4662] ;
As = [hi|_4656],
Bs = [_4660, bye|_4668] ;
As = [hi|_4656],
Bs = [_4660, _4666, bye|_4674] .

因此,整个问题都被误导了.在Prolog中进行编码时,请始终提出以下问题:如何制定应保留的内容?有了这样的表述之后,您就可以继续寻找Prolog引擎的解决方案了!

Hence, the whole question is somewhat misguided. When coding in Prolog, always ask: How can I formulate what ought to hold? Once you have such a formulation, you can leave the search for solutions to the Prolog engine!

如果您想 ,则可以更加明确.例如:

If you want, you can be more explicit. For example:


one_from_each([], _) --> [].
one_from_each([L|Ls], Rs) -->
    one_from_each_(Rs, L),
    one_from_each(Ls, Rs).

one_from_each_([], _) --> [].
one_from_each_([R|Rs], L) -->
    [[L,R]],
    one_from_each_(Rs, L).

示例:


?- phrase(one_from_each([hi,hello],[bye,later]), Ls).
Ls = [[hi, bye], [hi, later], [hello, bye], [hello, later]].

这有时称为空间表示形式,因为解决方案现在不再在回溯(时间表示形式)中找到,而是明确表示出来的.

This is sometimes called a spatial representation, because the solutions are now no longer found on backtracking (temporal representation), but represented explicitly.

由此可见,循环"对应于递归定义.

From this, you see that "loops" correspond to recursive definitions.

这篇关于Prolog:您如何在两个列表之间进行迭代(嵌套循环)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆