A REPL is an interactive programming environment that repeatedly reads input, evaluates it, and prints the result. In Clojure, clojure.main/repl starts the loop and can also serve as the foundation for customized interactive tools. section 22.4
Customize a REPL by supplying options for:
- Initialization, such as requiring a namespace or printing a welcome message before interaction begins. section 22.4
- The prompt, allowing a specialized message such as “enter expression :>”. section 22.4
- Reading and evaluation, allowing the loop to accept a restricted input format and dispatch operations itself. section 22.4
A calculator REPL
Define plus, minus, times, and divide, then initialize a nested REPL with those functions available. Evaluating (plus 1 2) prints 3. A more specialized configuration can read input such as 2*3, evaluate it, and print 6 before exiting with Ctrl+D. section 22.4
(require '[clojure.main :as main])
(def repl-options
[:prompt #(printf "enter expression :> ")
:read (fn [request-prompt request-exit] ; #1
(or ({:line-start request-prompt :stream-end request-exit} ; #2
(main/skip-whitespace *in*))
(re-find #"^(\d+)([\+\-\*\/])(\d+)$" (read-line)))) ; #3
:eval (fn [[_ x op y]] ; #4
(({"+" + "-" - "*" * "/" /} op)
(Integer. x) (Integer. y)))])
(apply main/repl repl-options)
;; enter expression :> 2*3 ; #5
;; 6
;; click ctrl+d to exit calculator
Inspect the complete custom calculator configuration, including prompt, input parsing, operator dispatch, numeric conversion, and evaluation. section 22.4





