将 System.out.format 翻译成 Clojure

Translate System.out.format to Clojure

我在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" 不起作用?

我就像一只猴子在键盘上打字希望能产生哈姆雷特!

请帮忙!谢谢。

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* 似乎被定义为 OutputStreamWriter,它没有 format 方法。不知道为什么,但是您可以使用绑定来解决这个问题,例如:

user=> (binding [*out* System/out]
         (. *out* format "abc %d" (into-array[12])))
abc 12#object[java.io.PrintStream 0x4efb0c88 "java.io.PrintStream@4efb0c88"]

Clojure 已经有一个 printf function that does the same thing as PrintStream.format, except that it prints specifically to *out*:

(printf "Enter number of points: ")
;; Enter number of points: 

(printf "abc %d" 12)
;; abc 12