summaryrefslogtreecommitdiff
path: root/prolog/calc
diff options
context:
space:
mode:
Diffstat (limited to 'prolog/calc')
-rw-r--r--prolog/calc32
1 files changed, 32 insertions, 0 deletions
diff --git a/prolog/calc b/prolog/calc
new file mode 100644
index 0000000..0ed11af
--- /dev/null
+++ b/prolog/calc
@@ -0,0 +1,32 @@
+{ CALC evaluates arithmetic expressions with store }
+
+calc:- eval ([], RS), write (result store), write (RS), nl.
+
+eval (SI, SO):-
+ read (CALC), nonvar (CALC), eval member (CALC, SI, SO).
+
+eval member (CALC, SI, SO):-
+ member (CALC, [stop,end,bye,eof]), SO=SI;
+ eval (CALC,I,SI,ST), write (I), eval (ST,SO);
+ write (error in), write (CALC), nl, eval (SI, SO).
+
+eval (I, I, S, S):- integer (I).
+eval (N, I, S, S):- atom (N), eval atom (N, I, S).
+
+eval atom (N, I, S):-
+ member (N=I, S);
+ write ("error: Cell"), write (N),
+ write("not found in store. 0 substituted."), nl, I=0.
+
+eval ( L+R,I,SI,SO):- eval (L,J,SI,ST), eval (R,K,ST,SO), I IS J+K.
+eval ( L-R,I,SI,SO):- eval (L,J,SI,ST), eval (R,K,ST,SO), I IS J-K.
+eval ( L*R,I,SI,SO):- eval (L,J,SI,ST), eval (R,K,ST,SO), I IS J*K.
+eval ( L/R,I,SI,SO):- eval (L,J,SI,ST), eval (R,K,ST,SO), I IS J/K.
+
+eval (N=O, I, SI, SO):-
+ atom (N), eval (O,I,SI,ST), eval repl (N,I,ST,SO).
+
+eval repl (N, I, [], [=(N,I)]).
+eval repl (N, I, [=(N,_)|S], [=(N,I)|S]).
+eval repl (N, I, [=(M,J)|SI], [=(M,J)|SO]):- eval repl (N, I, SI, SO).
+