Skip to content

Instantly share code, notes, and snippets.

@brenns10
Last active August 29, 2015 14:19
Show Gist options
  • Save brenns10/058ae723b30fee05d305 to your computer and use it in GitHub Desktop.
Save brenns10/058ae723b30fee05d305 to your computer and use it in GitHub Desktop.
Interpreter for C-like language subset, in Prolog, by Dr. Connamacher.
% m_state for while
m_state([while, C, B], S, S0) :- m_boolean(C, S), !,
m_state(B, S, S1),
m_state([while, C, B], S1, S0).
m_state([while, _, _], S, S).
% m_state for assignment
m_state([L, =, R], S, S0) :- remove_binding(L,S,S1),
m_value(R,S,V),
add_binding(L,V,S1,S0).
% m_state for a list of statements
m_state([H|R], S, S0) :- m_state(H, S, S1),
m_state(R, S1, S0).
m_state([], S, S).
% m_boolean
m_boolean(true, _).
m_boolean([E1, &&, E2], S) :- m_boolean(E1, S),
m_boolean(E2, S).
m_boolean([E1, ll, _], S) :- m_boolean(E1, S).
m_boolean([_, ll, E2], S) :- m_boolean(E2, S).
m_boolean([E1, <, E2], S) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V1 < V2.
m_boolean([E1, ==, E2], S) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V1 =:= V2.
m_boolean([E1, ><, E2], S) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V1 =\= V2.
m_boolean([E1, >, E2], S) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V1 > V2.
% m_value functions: numbers, variables, operations
m_value(E, _, E) :- number(E).
m_value(E, S, V) :- lookup(E, S, V).
m_value([E1, +, E2], S, V) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V is V1 + V2.
m_value([E1, -, E2], S, V) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V is V1 - V2.
m_value([E1, /, E2], S, V) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V is V1 // V2.
m_value([E1, *, E2], S, V) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V is V1 * V2.
m_value([E1, mod, E2], S, V) :- m_value(E1, S, V1),
m_value(E2, S, V2),
V is V1 rem V2.
% lookup
lookup(L, [[L,V]|_], V) :- !.
lookup(L, [_|R], V) :- lookup(L,R,V).
% add_bindings
add_binding(L, V, S0, [[L,V]|S0]).
% remove_bindings
remove_binding(L, [[L,_]|S], S).
remove_binding(L, [H|R], [H|S]) :- remove_binding(L,R,S).
remove_binding(_,[],[]).
% samples:
% m_state([[a, =, 72],[b, =, 64],[while, [b, ><, 0], [[r, =, [a, mod, b]], [a, =, b], [b, =, r]]]], [], S).
% m_state([[x,=,10],[result,=,1],[while,[x,>,0],[[result,=,[result,*,x]],[x,=,[x,-,1]]]]], [], S).
%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment