-
-
Save gbmele/4551ea3cd5cc2bad85ed5aa0d464d2b9 to your computer and use it in GitHub Desktop.
An example of closures (or "nested predicates") in Prolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%Since SWI-Prolog does not have a built-in implementation of closures, I wrote my own implementation here. | |
:- initialization(main). | |
:- set_prolog_flag('double_quotes','chars'). | |
main :- predicate_with_nested(1,C),writeln(C). | |
call_local(Definition,Params) :- | |
copy_term(Definition,(Params :- Body)), | |
call(Body). | |
predicate_with_nested(A,C) :- | |
Closure = ((B,C1) :- C1 is B+A), | |
A>0, | |
call_local(Closure,(1,C)), | |
call_local(Closure,(2,D)), | |
writeln(D). | |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | |
% | |
:- op(1200, xfx, ==>). | |
:- op(1000, xfy, /\). | |
:- op(1100, xfy, \/). | |
term_expansion(A ==> B, B:- A). | |
goal_expansion(A /\ B, (A, B)). | |
goal_expansion(A \/ B, (A; B)). | |
man(X) /\ unmarried(X) ==> bachelor(X). | |
man(john). | |
man(peter). | |
unmarried(john). | |
main:-bachelor(X), writeln(X), nl, fail. | |
It yields an answer now: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment