gpt4 book ai didi

java - 将 System.out.format 翻译成 Clojure

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:05:19 26 4
gpt4 key购买 nike

我已经用 Java 编写了一些实用程序,现在我只想将其翻译成 Clojure。我遇到了一些障碍类。 Clojure 宣称它可以与 Java 无缝互操作,但我没能从谷歌找到好的解决方案。请帮助。谢谢。

我想直接用Java类(不想用clojure“格式”功能还没有,因为我只是想看看如何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 分派(dispatch) var args 函数的方式是将其余参数插入 Object 数组。这可以像这样在 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。不知道为什么,但是您可以使用绑定(bind)来克服这个问题,例如:

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

关于java - 将 System.out.format 翻译成 Clojure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39012207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com