我已经用Java编写了一些实用程序,现在我只想把它翻译成Clojure。我在上课时遇到了一些麻烦。Clojure声称它与Java有着无缝的互操作,但是我还没有从Google那里找到好的解决方案。请帮帮忙。谢谢。
我想直接使用Java类(我还不想使用clojure的"format“函数,因为我只想看看clojure-java-interop是如何工作的):
System.out.format("Enter number of points: ");我所做的是:
(def x (. System out))但后来,我尝试使用格式的一切都失败了:
(. x format "foo")
(. x (format "foo"))
(.format x)
(.format "foo")
(. x format)
(. x #(format))
(. x #(format %) "s")
(.format x "foo")
((.format x) "foo")
(x/format "foo")
(x. format "%s" "foo")
(. x format "%s" "s")
(. x format "%s" ["s"])
(def y (System.out.))
(def y (System.out.format.))
(format x "s")那么将System.exit(0)转换为clojure又如何呢?
(. System exit 0) 确实很管用。但是为什么"System.out.format“的类似翻译不起作用呢?
我就像一只猴子在键盘上打字,希望制作哈姆雷特!
请帮帮忙!谢谢。
发布于 2016-08-18 07:48:04
System.out.format接受变量参数。java分派var args函数的方式是将其余的参数推入对象数组中。在clojure中可以实现这样的目标:
(. System/out format "abc" (into-array []))
(. System/out format "abc %d" (into-array [12]))
;; or use the more intuitive
(.format System/out "abc %d" (into-array[12]))实际上,你的很多尝试都非常接近:
(def x (. System out))
(. x format "foo" (into-array[]))
(. x (format "foo" (into-array[])))
(.format x "foo" (into-array[]))
(. x format "%s" (into-array["foo"]))但是,请注意,这将打印到repl控制台,而不一定是您的ide显示的内容。
要像clojure那样展示它,不要使用java的System.out对象,而是使用clojure的*out*
(. *out* format "abc %d" (into-array [12]))
;; "abc 12"编辑
您的*out*似乎被定义为没有方法format的OutputStreamWriter。不确定原因,但您可以使用绑定来克服这一问题,例如:
user=> (binding [*out* System/out]
(. *out* format "abc %d" (into-array[12])))
abc 12#object[java.io.PrintStream 0x4efb0c88 "java.io.PrintStream@4efb0c88"]发布于 2016-08-18 11:58:10
Clojure已经有了一个printf函数,它执行与PrintStream.format相同的操作,只是它专门打印到*out*。
(printf "Enter number of points: ")
;; Enter number of points:
(printf "abc %d" 12)
;; abc 12https://stackoverflow.com/questions/39012207
复制相似问题