liveBook · Manning

Read-execute-print loop

As explained in Clojure: The Essential Reference

A REPL is an interactive programming environment that repeatedly reads input, evaluates it, and prints the result.

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

How Clojure: The Essential Reference covers it

How deep it goes
Explains the loop and demonstrates initialization, prompting, reading, parsing, and evaluation without detailing internal implementation.
Examples
Uses a calculator with named arithmetic functions and a parser for expressions such as 2*3.
What it assumes
Assumes basic Clojure functions and namespaces while demonstrating REPL customization through arithmetic examples.
What you can do after
Build it from scratch as a customized Clojure REPL with tailored startup, prompt, input, and evaluation behavior.
How it connects
Connects REPLs with clojure.main, clojure.repl, namespaces, command-line entry points, and server socket functionality.

Also explained in

Compare how 6 books explain read-execute-print loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.