about summary refs log tree commit diff stats
path: root/js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm
diff options
context:
space:
mode:
authorelioat <elioat@tilde.institute>2023-08-23 07:52:19 -0400
committerelioat <elioat@tilde.institute>2023-08-23 07:52:19 -0400
commit562a9a52d599d9a05f871404050968a5fd282640 (patch)
tree7d3305c1252c043bfe246ccc7deff0056aa6b5ab /js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm
parent5d012c6c011a9dedf7d0a098e456206244eb5a0f (diff)
downloadtour-562a9a52d599d9a05f871404050968a5fd282640.tar.gz
*
Diffstat (limited to 'js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm')
-rw-r--r--js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm29
1 files changed, 29 insertions, 0 deletions
diff --git a/js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm b/js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm
new file mode 100644
index 0000000..7d667dd
--- /dev/null
+++ b/js/games/nluqo.github.io/~bh/61a-pages/Lib/calc.scm
@@ -0,0 +1,29 @@
+;; Scheme calculator -- evaluate simple expressions
+
+; The read-eval-print loop:
+
+(define (calc)
+  (display "calc: ")
+  (flush)
+  (print (calc-eval (read)))
+  (calc))
+
+; Evaluate an expression:
+
+(define (calc-eval exp)
+  (cond ((number? exp) exp)
+	((list? exp) (calc-apply (car exp) (map calc-eval (cdr exp))))
+	(else (error "Calc: bad expression:" exp))))
+
+; Apply a function to arguments:
+
+(define (calc-apply fn args)
+  (cond ((eq? fn '+) (accumulate + 0 args))
+	((eq? fn '-) (cond ((null? args) (error "Calc: no args to -"))
+			   ((= (length args) 1) (- (car args)))
+			   (else (- (car args) (accumulate + 0 (cdr args))))))
+	((eq? fn '*) (accumulate * 1 args))
+	((eq? fn '/) (cond ((null? args) (error "Calc: no args to /"))
+			   ((= (length args) 1) (/ (car args)))
+			   (else (/ (car args) (accumulate * 1 (cdr args))))))
+	(else (error "Calc: bad operator:" fn))))