Fork me on GitHub
#beginners
<
2021-06-07
>
Chris K03:06:40

How can I make a repl using clojure? Any help? THis is my current code but doesn't work 😞

(defn print-prompt [s]
  (print (str "\n" s)))

(defn get-user-input
  []
  (read-line))

(defn repl-loop
  []
  (while true
    (do
      (print "REPL>>")
      (print-prompt (get-user-input)))))

dpsutton03:06:39

you need to invoke the reader and then eval.

dpsutton03:06:48

(println (eval (read-string (get-user-input)))) ReadEvalPrintLoop

seancorfield03:06:57

@sunchaesk This is how Clojure's REPL is implemented: https://github.com/clojure/clojure/blob/38524061dcb14c598c239be87184b3378ffc5bac/src/clj/clojure/main.clj#L456-L466 -- the source code can be an interesting read sometimes when you're trying to figure out how to do similar things.

Chris K03:06:49

@seancorfield sorry to bother, but could there be like a simple code that works? and maybe I will try improving from it? I just can't seem to make a simple one work

solf04:06:20

@U11BV7MTK wrote a working code in the comment just above

dpsutton04:06:48

user=> (while true (println (eval (read-string (read-line)))))
(+ 1 1)
2
(let [x 1] (+ x 2))
3

Chris K04:06:38

oh shoot didn't see that

Chris K04:06:42

thank you so much

Chris K03:06:39

@seancorfield Thank you so much I never really thought about it 😄

popeye07:06:31

What macros do which functions cannot do, I meant (when to use macros and when to use functions)

teodorlu10:06:24

Macros allow you to capture expressions before you're evaluated.

(f x)
If f is a function, you'll have access to the value of x. If f is a macro, you'll be able to know that its name is x and not y.

teodorlu10:06:21

(defn f-function [x]
  (+ x x))

(defmacro f-macro [x]
  (cond (= x 'x) :x
        (= x 'y) :y
        :else `(f-function ~x)))

(f-function 10)
;; => 20

(f-macro 10)
;; => 20

(let [x 10]
  (f-function x))
;; => 20

(let [x 10]
  (f-macro x))
;; => :x

Rob Haisfield14:06:42
replied to a thread:

This is really helpful, thank you