Skip to content

Commit

Permalink
feat: adding do clause to run multiple expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
BRonen committed Mar 31, 2024
1 parent b7e427e commit 3a99e0c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
14 changes: 9 additions & 5 deletions src/bronen/kekwisp.clj
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,10 @@
; Evaluation

(def default-context
{"def" (fn [v] {:token "definition" :value v})
{"print" (fn [v] {:token "print" :value v})
"def" (fn [v] {:token "definition" :value v})
"fn" (fn [v] {:token "function" :value v})
"do" (fn [v] {:token "do" :value v})
"+" (fn [v] {:token "sum" :value v})
"-" (fn [v] {:token "subtraction" :value v})
"*" (fn [v] {:token "multiplication" :value v})
Expand All @@ -103,14 +105,16 @@
[values ctx]
(let [f (evaluate (first values) ctx)]
(case (:token f)
"definition" (do (swap! ctx #(conj % {(:value (nth values 1))
(:value (nth values 2))}))
(when (nth values 3 false) (evaluate (nth values 3) ctx)))
"callable" ((:value f) (map #(evaluate % ctx) (drop 1 values)))
"sum" (apply + (map #(evaluate % ctx) (drop 1 values)))
"subtraction" (apply - (map #(evaluate % ctx) (drop 1 values)))
"multiplication" (apply * (map #(evaluate % ctx) (drop 1 values)))
"division" (apply / (map #(evaluate % ctx) (drop 1 values)))
"callable" ((:value f) (map #(evaluate % ctx) (drop 1 values)))
"print" (let [result (doall (map #(evaluate % ctx) (drop 1 values)))] (println result) result)
"do" (last (doall (map #(evaluate % ctx) (drop 1 values))))
"definition" (do (swap! ctx #(conj % {(:value (nth values 1))
(evaluate (nth values 2))}))
(when (nth values 3 false) (evaluate (nth values 3) ctx)))
"function" {:token "callable"
:value (fn [args]
(let [params (map :value (:value (nth values 1)))
Expand Down
10 changes: 9 additions & 1 deletion test/bronen/kekwisp_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,12 @@
(parse)
(first)
(#(evaluate % ctx)))
245)))))
245))))
(testing "Should evaluate multiple expressions"
(let [ctx (atom {})]
(is (= (-> "(do (def addtwo (fn (a b) (+ a b))) (addtwo 1 2) (addtwo 23 44))"
(lexer)
(parse)
(first)
(#(evaluate % ctx)))
67)))))

0 comments on commit 3a99e0c

Please sign in to comment.