Question

I have defined some custom constraints like that:

constraint(a,something).
constraint(a,something1).
constraint(a,something2).

and i need this logical conjunction of them all as a result. ( if one constraint fails, the result should fail )

result(X) :-
    constraint(X,something),
    constraint(X,something1),
    constraint(X,somethingElse).

I'm looking for a more convenient way to avoid this explicit coding of all constraints.

result(X) :- ????
Was it helpful?

Solution 2

At some point, you need a predicate somewhere to actually list all the constraints you wish to apply. You could do something like this:

result(X) :-
    constraints(X, [something, something1, something2]).

constraints(X, [H|T]) :-
    constraint(X, H),
    constraints(X, T).
constraints(_, []).

This mechanism allows you to generate the constraints dynamically as a list, if desired. You could also have the list of constraints be a fact:

constraint_list(a, [something, something1, something2]).

And then use that in the result predicate:

result(X) :-
    constraint_list(X, List),
    constraints(X, List).

OTHER TIPS

Consider using maplist/2:

all_true(X) :- maplist(constraint(X), [something, something1, something2]).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top