I'm wondering: what is the best way to write a Clojure program that interacts with a user or another program thorough stdin and stdout?
Clearly it would be possible to write some kind of imperative loop, but I'm hoping to find something more lazy / functional, a bit inspired by Haskell's "interact" function.
This was the best I could come up with:
(defn interact [f]
(lazy-seq
(cons (do (let [input (read-line)
result (f input)]
(println result)
{:input input :result result}))
(interact f))))
You could use it like this:
(def session
(take-while #(not= (:result %) 0)
(interact count)))
REPL:
user=> (str "Total Length: " (reduce #(+ %1 (:result %2)) 0 session))
foobar
6
stackoverflow
13
0
"Total Length: 19"
user=> session
({:input "foobar", :result 6} {:input "stackoverflow", :result 13})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With