如何在prolog中模拟嵌套循环?

moh*_*mad 3 prolog nested-loops

我怎样才能在Prolog中模拟这段代码?

// L = an existing list ; 
// function foo(var X, var Y)
result = new List();
for(int i=0;i<L.length;i++)
    for(int j=0;j<L.length;j++){
        result.add(foo(L.get(i), L.get(j));
    }
Run Code Online (Sandbox Code Playgroud)

Cap*_*liC 5

嵌套循环基本上是序列之间的连接,并且Prolog中的大多数列表处理最好在没有索引的情况下表示:

?- L=[a,b,c], findall(foo(X,Y), (member(X,L),member(Y,L)), R).
L = [a, b, c],
R = [foo(a, a), foo(a, b), foo(a, c), foo(b, a), foo(b, b), foo(b, c), foo(c, a), foo(c, b), foo(..., ...)].
Run Code Online (Sandbox Code Playgroud)

编辑

有时整数允许以简单的方式捕获含义.作为一个例子,我的解决方案是一个更简单的Prolog上下文测验.

icecream(N) :-
    loop(N, top(N)),
    left, loop(N+1, center), nl,
    loop(N+1, bottom(N)).

:- meta_predicate loop(+, 1).

loop(XH, PR) :-
    H is XH,
    forall(between(1, H, I), call(PR, I)).

top(N, I) :-
    left, spc(N-I+1), pop,
    (   I > 1
    ->  pop,
        spc(2*(I-2)),
        pcl
    ;   true
    ),
    pcl, nl.

bottom(N, I) :-
    left, spc(I-1), put(\), spc(2*(N-I+1)), put(/), nl.

center(_) :- put(/), put(\).

left :- spc(4).
pop :- put(0'().
pcl :- put(0')).
spc(Ex) :- V is Ex, forall(between(1, V, _), put(0' )).
Run Code Online (Sandbox Code Playgroud)

在SWI-Prolog中运行:

?- icecream(3).
       ()
      (())
     ((  ))
    /\/\/\/\
    \      /
     \    /
      \  /
       \/
true.


?- forall(loop(3,[X]>>loop(2,{X}/[Y]>>writeln(X-Y))),true).
1-1
1-2
2-1
2-2
3-1
3-2
true.
Run Code Online (Sandbox Code Playgroud)