/
๐Ÿ‘‹

Stack Based Interpreter In Clojure - Part 2

https://nerds-den.com/stack-based-interpreter-in-clojure-part-2
clojuredata-structionsstackinterpreter

In part one we didn't delve into any code. Let's fix that now.

If you are an impatient soul and wish to jump onto the completed source code, you can find it here

The first thing you need to build a stack machine. Stack machine is a stack: a data structure that we can push and pop operands into/out of. Because we are using Clojure that means we're going to use a List and we need it to be generic.

(defprotocol IStack
(empty? [this])
(push [this item])
(pop [this])
(peek [this])
(get [this])
(set [this stack])
(clear-stack [this]))
(defrecord Stack [stack]
IStack
(empty? [this]
(clojure.core/empty? (get-in this [:stack])))
(push [this item]
(update-in this [:stack] conj item))
(pop [this]
(as-> this $
(update-in $ [:stack] clojure.core/pop)))
(peek [this]
(first (get-in this [:stack])))
(get [this]
(-> this :stack))
(set [this stack]
(assoc this :stack stack))
(clear-stack [this]
(assoc this :stack (clojure.core/empty (:stack this)))))
(defn make-stack []
(map->Stack {:stack '()}))

In the next part we will figure out what is an instruction, how to build one, and initiate an instruction table to store them.

Algorithms & Data Structures In Clojure(Script)