Clojure中避免侵入式println 借助REPL输出多表达式求值结果方案
问题描述
假设我们需要对源文件中的多个子句进行求值,例如test.clj文件内容如下:
@(def x 1) @(def y 2) @(def z 3)
如果直接使用clj或者lein repl加载文件,只会显示最后一个表达式的求值结果:
user => (load-file "test.clj") 3
我们可以给每个表达式套上println来输出所有结果,修改为test-with-println.clj:
(println @(def x 1)) (println @(def y 2)) (println @(def z 3))
加载后输出:
user => (load-file "test-with-println.clj") 1 2 3 nil
有没有更优的方案,既不需要在源码中到处编写侵入式的println,又可以在REPL环境下输出所有需要的求值结果?
解决方案
借助Sean Corfield提到的tap>功能即可实现需求,操作步骤如下:
- 将所有需要打印的表达式结果传给
tap>,修改为test-with-tap.clj:
(-> @(def x 1) tap>) (-> @(def y 2) tap>) (-> @(def z 3) tap>)
- 在通过
add-tap开启tap>监听前,REPL不会输出对应结果:
user=> (load-file "test-with-tap.clj") nil user=> (add-tap @(def out (bound-fn* println))) nil user=> (load-file "test-with-tap.clj") 1 2 3 user=> (remove-tap out) nil user=> (load-file "test-with-tap.clj") nil
内容的提问来源于stack exchange,提问作者sof
相关产品推荐
相关产品推荐

