Created
August 17, 2024 21:24
-
-
Save GeoffChurch/50a1c871f42c7c1650a527bcb5d0c08b to your computer and use it in GitHub Desktop.
Prolog getters, setters, mutators using term_expansion
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
user:term_expansion((:- derive_accessors(ClassTemplate)), Clauses) :- | |
ClassTemplate =.. [ClassName|Fields], | |
functor(ClassTemplate, ClassName, Arity), | |
functor(Skel, ClassName, Arity), | |
term_variables(Skel, Vars), | |
foldl(build_accessors(Skel), Fields, Vars, [], Clauses). | |
return(G), [Ret] --> { call(G, Ret) }. | |
build_accessors(Skel, Field, Var) --> | |
foldl(return, [derive_get(Skel, Field, Var), | |
derive_dcg_get(Skel, Field, Var), | |
derive_set(Skel, Field, Var), | |
derive_mut(Skel, Field, Var)]). | |
derive_get(Skel, Field, Var, Ret) :- | |
atom_concat(get_, Field, GetF), | |
Ret =.. [GetF, Var, Skel]. | |
derive_dcg_get(Skel, Field, Var, Ret) :- | |
atom_concat(dcg_, Field, GetF), | |
Ret =.. [GetF, Var, Skel, Skel]. | |
derive_set(Skel, Field, Var, Ret) :- | |
copy_term([Var], Skel, [Var_], Skel_), | |
atom_concat(set_, Field, SetF), | |
Ret =.. [SetF, Var_, Skel, Skel_]. | |
derive_mut(Skel, Field, Var, Ret) :- | |
copy_term([Var], Skel, [Var_], Skel_), | |
atom_concat(mut_, Field, MutF), | |
Head =.. [MutF, Goal, Skel, Skel_], | |
Ret = (Head :- call(Goal, Var, Var_)). | |
% Example: | |
% :- derive_accessors(employee(name, salary)). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment