我想知道:编写与用户或其他程序通过stdin和stdout交互的Clojure程序的最佳方式是什么?
显然,可以编写某种命令式循环,但我希望找到更懒惰/函数式一些的东西,有点取自Haskell的“interact”函数的灵感。
我想知道:编写与用户或其他程序通过stdin和stdout交互的Clojure程序的最佳方式是什么?
显然,可以编写某种命令式循环,但我希望找到更懒惰/函数式一些的东西,有点取自Haskell的“interact”函数的灵感。
(defn interact [f]
(lazy-seq
(cons (do (let [input (read-line)
result (f input)]
(println result)
{:input input :result result}))
(interact f))))
(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})