如何在 clojure 中创建一个简单的用户提示符
How to create a simple userprompt in clojure
考虑一下 clojure 中这个非常简单的函数定义:
(defn prompt []
(print ">>> ")
(read-line))
我的目标是让用户输入一个带有提示前缀的字符串。但是,似乎 read-line
在 print
语句之前执行。但是,通过刷新输出流
(defn prompt []
(print ">>> ")
(flush)
(read-line))
此功能按预期工作。为什么我必须手动刷新 out 才能写出“>>>”?根据文档,函数和 do
应该按顺序执行表达式。
您可以使用 println
而不是 print
来理解您的意思:
(defn prompt []
(println ">>> ")
(read-line))
区别在于pr
在(source print)
中的用法,在(source println)
中使用了prn
。查看源代码。
它们是按顺序执行的。但是执行 print
并不意味着给定的输出将刷新到 *out*
变量指向的任何流。正如文档所说,print
函数
Prints the object(s) to the output stream that is the current value
of *out*.
默认情况下,*out* 指向一个 PrintWriter
that is generally the target of System.out
. With the PrintWriter
instances, flushing isn't enabled by default. Although, you can enable auto-flush via by using certain constructors 用于创建实例。
即便如此,PrintWriter
个实例:
if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.
考虑一下 clojure 中这个非常简单的函数定义:
(defn prompt []
(print ">>> ")
(read-line))
我的目标是让用户输入一个带有提示前缀的字符串。但是,似乎 read-line
在 print
语句之前执行。但是,通过刷新输出流
(defn prompt []
(print ">>> ")
(flush)
(read-line))
此功能按预期工作。为什么我必须手动刷新 out 才能写出“>>>”?根据文档,函数和 do
应该按顺序执行表达式。
您可以使用 println
而不是 print
来理解您的意思:
(defn prompt []
(println ">>> ")
(read-line))
区别在于pr
在(source print)
中的用法,在(source println)
中使用了prn
。查看源代码。
它们是按顺序执行的。但是执行 print
并不意味着给定的输出将刷新到 *out*
变量指向的任何流。正如文档所说,print
函数
Prints the object(s) to the output stream that is the current value of *out*.
默认情况下,*out* 指向一个 PrintWriter
that is generally the target of System.out
. With the PrintWriter
instances, flushing isn't enabled by default. Although, you can enable auto-flush via by using certain constructors 用于创建实例。
即便如此,PrintWriter
个实例:
if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.