Skip to content

Instantly share code, notes, and snippets.

@jarble
Last active February 8, 2024 09:05
Show Gist options
  • Save jarble/8f8f80fa60b089d551efb0c6a74be45b to your computer and use it in GitHub Desktop.
Save jarble/8f8f80fa60b089d551efb0c6a74be45b to your computer and use it in GitHub Desktop.
An example of closures (or "nested predicates") in Prolog
%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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment