mik*_*era 18 command-line functional-programming interactive clojure lazy-evaluation
我想知道:编写与用户或其他程序通过stdin和stdout交互的Clojure程序的最佳方法是什么?
显然,有可能编写某种命令式循环,但我希望找到一些更懒惰/功能的东西,有点受Haskell的"交互"功能的启发.
这是我能想到的最好的:
(defn interact [f]
(lazy-seq
(cons (do (let [input (read-line)
result (f input)]
(println result)
{:input input :result result}))
(interact f))))
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
(def session
(take-while #(not= (:result %) 0)
(interact count)))
Run Code Online (Sandbox Code Playgroud)
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})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
698 次 |
最近记录: |