run function with all possibilities resulted from other function

1.3k views Asked by At

I have two predicates:

foo(Y,X)
bar(Y,Z)

After running foo, How can I run bar with all possibilities of Y ?

example:

foo(Y, key) % all possibilities of Y => chat 
            %                           faq 
            %                           about
            %                           search

How can I run bar with these all possibilities ?

bar(chat, Z)
bar(faq, Z)
bar(about, Z)
bar(serach, Z)

And then store all the results of Z in a list Zs?

3

There are 3 answers

2
m09 On BEST ANSWER
allZs(X, Zs) :-
    setof(Y, foo(Y, X), Ys),
    maplist(bar, Ys, Zs).

related SWI-Prolog man pages: Finding all Solutions to a Goal and library apply

Note: usually in Prolog the convention is to put intput arguments before output ones - in your first predicate that'd mean foo(X, Y) instead of foo(Y, X). Plus here it'd outline the transitivity: foo(X, Y), bar(Y, Z)..

2
Sufian Latif On

I think you want something like this:

barOnList([], []).
barOnList([Y|Ys], [Z|Zs]) :- bar(Y, Z), barOnList(Ys, Zs).
0
CapelliC On

foo/2 and bar/2 are already in join, and after each run of foo/2 bar/2 will be tried.

Maybe you are looking for forall(foo(Y,X), bar(Y,Z)), that run all possibilities of foo/2, and then bar/2. I.e. is required that bar/2 doesn't fail.

To understand the behaviour of forall/2, as well as other all solutions builtins, like setof/3, can be useful test with very simple builtins, with well known behaviour:

?- forall(member(X,[f,o,o]),(member(Y,[b,a,r]),writeln(X-Y))).
f-b
o-b
o-b
true.

You can see that the complete solution search of forall applies to its first argument, not the second.

HTH