run function with all possibilities resulted from other function

[亡魂溺海] 提交于 2019-12-10 23:53:35

问题


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?


回答1:


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:


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




回答3:


I think you want something like this:

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


来源:https://stackoverflow.com/questions/10844782/run-function-with-all-possibilities-resulted-from-other-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!