From fc3911c68a4a8a0ff916b858e5fe029ed2ebe493 Mon Sep 17 00:00:00 2001 From: nea Date: Wed, 9 Aug 2023 17:29:32 +0200 Subject: Add more arithmetic operations --- src/CoreBindings.kt | 42 +++++++++++++++++++++++++++++++++++++++++- test/res/test.lisp | 5 ++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/CoreBindings.kt b/src/CoreBindings.kt index 13c6de3..645a4ae 100644 --- a/src/CoreBindings.kt +++ b/src/CoreBindings.kt @@ -92,7 +92,7 @@ object CoreBindings { is LispData.LispNode -> resolved.node.toSource() is LispData.LispString -> resolved.string is LispData.LispNumber -> resolved.value.toString() - is LispData.LispInterpretedCallable -> "" + is LispData.LispInterpretedCallable -> ""} ${resolved.argNames} ${resolved.body.toSource()}>" } }) LispData.LispNil @@ -106,9 +106,49 @@ object CoreBindings { ?: return@externalCall reportError("Unexpected argument $b, expected number")).value }) } + val sub = LispData.externalCall { args, reportError -> + if (args.size == 0) { + return@externalCall reportError("Cannot call sub without at least 1 argument") + } + val c = args.map { + (it as? LispData.LispNumber + ?: return@externalCall reportError("Unexpected argument $it, expected number") + ).value + } + LispData.LispNumber(args.drop(1).fold(c.first()) { a, b -> + a - (b as? LispData.LispNumber + ?: return@externalCall reportError("Unexpected argument $b, expected number")).value + }) + } + val mul = LispData.externalCall { args, reportError -> + if (args.size == 0) { + return@externalCall reportError("Cannot call mul without at least 1 argument") + } + LispData.LispNumber(args.fold(1.0) { a, b -> + a * (b as? LispData.LispNumber + ?: return@externalCall reportError("Unexpected argument $b, expected number")).value + }) + } + val div = LispData.externalCall { args, reportError -> + if (args.size == 0) { + return@externalCall reportError("Cannot call div without at least 1 argument") + } + val c = args.map { + (it as? LispData.LispNumber + ?: return@externalCall reportError("Unexpected argument $it, expected number") + ).value + } + LispData.LispNumber(args.drop(1).fold(c.first()) { a, b -> + a / (b as? LispData.LispNumber + ?: return@externalCall reportError("Unexpected argument $b, expected number")).value + }) + } fun offerArithmeticTo(bindings: StackFrame) { bindings.setValueLocal("+", add) + bindings.setValueLocal("/", div) + bindings.setValueLocal("*", mul) + bindings.setValueLocal("-", sub) } fun offerAllTo(bindings: StackFrame) { diff --git a/test/res/test.lisp b/test/res/test.lisp index 06e9f43..cc20808 100644 --- a/test/res/test.lisp +++ b/test/res/test.lisp @@ -5,4 +5,7 @@ (debuglog a) (def helloworld (pure "hello world")) (debuglog helloworld (helloworld)) -(debuglog + (+ 1.2 15)) +(debuglog "+" (+ 1.2 15)) +(debuglog "-" (- 1 3)) +(debuglog "*" (* 10 10)) +(debuglog "/" (/ 1 3 2)) -- cgit