Create a complex predicate from a list in Prolog

If I have a predicate list in Prolog, for example [flies, swims], how can I build a predicate that is the conjunction of all the predicates in the list, i.e. fliesAndSwims(X) :- flies(X), swims(X).?

Alternatively, is there a better way to create a predicate at runtime, like this, without putting the predicates of the components in the list and without creating a compound one if necessary?

EDIT: So it turns out that this is a duplicate of the predicate list in Prolog . Earlier, I found this answer, but I thought that it only returned whether the given atom corresponded to each predicate in the list. I did not understand that you can pass a variable instead of an atom and return it every case that also matches.

+4
source share
2 answers

the library (lambda) is powerful, but it has value. If you think “easier is better” (debugging debugging, especially ...), consider

call_unary_list([], _).
call_unary_list([P|Ps], X) :-
    call(P, X),
    call_unary_list(Ps, X).

compare indicators:

compare_call_list :-
    findall(flies, between(1,100000,_), L),
    time(call_unary_list(L, _)),
    time(maplist(call_unary(_), L)),
    time(maplist(X+\Pred^call(Pred,X), L)).

call_unary(X, P) :- call(P, X).

?- compare_call_list.
% 200,000 inferences, 0.123 CPU in 0.123 seconds (100% CPU, 1629657 Lips)
% 300,000 inferences, 0.145 CPU in 0.149 seconds (98% CPU, 2064184 Lips)
% 1,000,001 inferences, 1.286 CPU in 1.297 seconds (99% CPU, 777362 Lips)
true .

call_unary / 2 allocates the argument swap required by the maplist meta test

+2
source

Here's an alternative to updating the Prolog dynamic database ... you can use a meta predicate , for example maplist/2, IMHO fits perfectly with the Prolog lambda expressions .

First, some examples of (super-incomplete) definitions flies/1and swims/1:

flies(duck).
flies(eagle).

swims(penguin).
swims(ostrich).
swims(duck).
swims(kiwi).
swims(eagle).

Now let's make a request:

?- use_module(library(lambda)).
true.

?- maplist(X+\Pred^call(Pred,X), [flies,swims]).
X = duck ;
X = eagle.
+2
source

Source: https://habr.com/ru/post/1584725/


All Articles