0

After I have seen these question, I have tried to solve below problem. But I could not solve it. Can anyone help me ?

predefined :

   foo( X, Y )        bar( Y, Z )
        ^  ^               ^  ^
      all of them is atomic, that is they only return or take one value at a time

   sample example:

      foo(john, brad).
      bar(john, marry).

      foo( Y, brad)   

      Y = john   % after pressing a, all possibilities will be seen at terminal

      bar(Y, Z )

      Z = marry  % after pressing a, all possibilities will be seen at terminal

   %..................

For these case how can I run bar with all possibilities of Y, resulted after eash run of foo ?

Community
  • 1
  • 1
user1428237
  • 49
  • 1
  • 6

1 Answers1

0

If bar/2 is a predicate that results in certain side effects, such as input-output, being produced, then that is what backtracking is for.

You just say:

   ?- foo(X,Y),bar(Y,Z).

And get all the possibilities, pressing a or ; depending on your implementation.

Alternatively, you can write

   ?- foo(X,Y),bar(Y,Z),write(bar(Y,Z)),nl,fail.

On the other hand, if you need to check if there is a bar(Y,Z) pair for every Y that satisfies foo(X,Y), than you can use Prolog forall/2 facility. For instance, the following goal will be true only if for every Y that results from foo(X,Y), there exists a Z that satisfies bar(Y,Z).

   ?- forall(foo(X,Y),bar(Y,Z)).

Examples

Given the following facts

foo(a,b).
foo(a,c).
bar(c,x).
bar(c,y).

With the first goal you get

?- foo(X,Y),bar(Y,Z),write(bar(Y,Z)),nl,fail.
bar(c,x)
bar(c,y)
false.

With the second goal:

?- forall(foo(X,Y),bar(Y,Z)).
false.

Since the goal bar(b,Z). fails.

Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76