% ================================================================= % == == % == An Introduction to ARTIFICIAL INTELLIGENCE == % == Janet Finlay and Alan Dix == % == UCL Press, 1996 == % == == % ================================================================= % == == % == meta-logical predicates == % == == % == Prolog example, Alan Dix, August 1996 == % == == % ================================================================= % Defines: % findall/3, findone/2, sumall/3, maxall/3, retractall/1, in_range/3 % Uses: % range_list/3, member/2 from file 'list.p' % Please: % consult('list.p'). % some of the predicates defined here may be in standard Prolog % libraries or be built-in predicates. % findall(X,Goal,S) builds a set in S of all the instantiations % of the variable/term X such that Goal is true. % Normally Goal will be a predicate containg the variable X, % or X and Goal will share some other free variable. % This will almost certainly be pre-defined in your Prolog % in which case, comment out this definition before consulting % this file. % code based on find_all_dl in "The Art of Prolog 2nd Ed.", p 304 % Stirling and Shapiro, MIT Press, 1994 findall(X,Goal,_) :- asserta('$X'('$mark')), % marker so collect can tell Goal, % when it should finished asserta('$X'(X)), fail. % forces a retry of Goal findall(_,_,S) :- collect(S). collect(S) :- retract('$X'(X)), collect2(X,S), !. collect2(X,[X|S]) :- not X = '$mark', retract('$X'(X1)), !, collect2(X1,S). collect2('$mark',[]). % findone(X,Goal) simply looks for one solution, however, it does so % without causing any bindings apart from that for X. % Normally Goal will be a predicate containg the variable X, % or X and Goal will share some other free variable. findone(X,Goal) :- findone2(X,Goal,Flag), % findone2 always succeeds !, Flag=goal_ok. % flag indicates success findone2(X,Goal,goal_fail) :- findone1(X,Goal), % findone1 only succeeds if Goal !. % has failed. If findone1 has failed, findone2(X,_,goal_ok) :- % then Goal has succeeded and '$X' retract('$X'(X)). % records the required value. findone1(X,Goal) :- Goal, asserta('$X'(X)), % record X if successful !, fail. findone1(_,_). % succeed if Goal fails % sumall(N,Goal,Sum) finds all numbers N satisfying the goal % and adds them together. sumall(N,Goal,Sum) :- findall(N,Goal,L), sumlist(L,Sum). % sumall(N,Goal,Sum) finds the maximum of all numbers N % which satisfy the goal % fails if none are found maxall(N,Goal,Max) :- findall(N,Goal,L), maxlist(L,Max). % retractall(P) retracts all clauses matching P retractall(P) :- retract(P), fail. retractall(P). % in_range(Var,Lo,Hi) binds Var in turn to the numbers Lo...Hi in_range(V,Lo,Hi) :- range_list(Lo,Hi,L), % defined in 'list.p' member(V,L). % RUNNING THIS CODE %