在Clojure中编写一个惰性的,功能性的,交互式的命令行应用程序

时间:2011-03-30 12:25:29

标签: command-line functional-programming clojure lazy-evaluation interactive

我想知道:编写与用户或其他程序通过stdin和stdout交互的Clojure程序的最佳方法是什么?

显然,有可能编写某种命令式循环,但我希望找到一些更懒惰/功能性的东西,有点受Haskell“交互”功能的启发。

1 个答案:

答案 0 :(得分:5)

这是我能想到的最好的:

(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})