Skip to content

Instantly share code, notes, and snippets.

@jeshan

jeshan/state.pl

Created Apr 3, 2021
Embed
What would you like to do?
Pure way for tracking state of variables in Prolog
% get_value(Value, History)
% History tracks values set for variable
get_value(Val, List) :-
nonvar(List), % just so that fails when nothing added yet.
nextto(t(Val), Var, List),
var(Var),
!.
available_spot(X, History) :-
once((member(X, History), var(X))).
add_value(Val, History) :-
available_spot(X, History),
t(Val) = X.
@jeshan

This comment has been minimized.

Copy link
Owner Author

@jeshan jeshan commented Apr 3, 2021

Example outputs:

?- get_value(X, History).
false.

?- add_value(abc, History).
History = [t(abc)|_2856].

?- add_value(abc, History), get_value(Current, History).
History = [t(abc), _5110|_5112],
Current = abc.

?- add_value(3, History), get_value(FirstWas, History), add_value('my-symbol', History), get_value(SecondWas, History), add_value(2, History), add_value(AVar, History), get_value(LatestIs, History), LatestIs = xyz.
History = [t(3), t('my-symbol'), t(2), t(xyz), _1946|_1948],
FirstWas = 3,
SecondWas = 'my-symbol',
AVar = LatestIs, LatestIs = xyz.
@jeshan

This comment has been minimized.

Copy link
Owner Author

@jeshan jeshan commented Apr 3, 2021

Code is released to the public domain

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment