【问题标题】:Writing a lazy, functional, interactive command line application in Clojure在 Clojure 中编写一个惰性、功能性、交互式的命令行应用程序
【发布时间】:2023-12-21 12:30:01
【问题描述】:

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

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

【问题讨论】:

  • 这是一个令人惊讶的难题。也许社区需要 clojure.contrib.interact

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


【解决方案1】:

这是我能想到的最好的:

(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
*
13

0
"Total Length: 19"
user=> session
({:input "foobar", :result 6} {:input "*", :result 13})

【讨论】: