18

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.

1
  • 2
    This is a surprisingly hard question. perhaps the community needs clojure.contrib.interact Commented Mar 31, 2011 at 18:42

1 Answer 1

5

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})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.