Clojure - 副作用发生乱序 [英] Clojure - Side Effects Happening Out Of Order
问题描述
在Clojure中,我编写了一个非常基本的程序来回应用户键入的内容。然而,它不以我认为是自然的方式运行。这里是代码:
While dabbling in Clojure I've written a very basic program to echo whatever the user types into it. However, it doesn't run in a way that I'm perceiving to be natural. Here's the code:
(defn goo []
(print "echo> ")
(def resp (read-line))
(print resp)
)
(对于我输入 foo
作为 read-line
的输入):
user=> (goo)
echo> foo
foonil
但是,回显和读取线被切换:
But instead, the echo and read-line is switched:
user=> (goo)
foo
echo> foonil
为什么会发生这种情况?
Why does this happen? Is there a subtlety I'm missing?
编辑:从Joe的答案,更新的正确解决方案是:
From Joe's answer, the updated correct solution is:
(defn goo []
(print "echo> ")
(flush)
(def resp (read-line))
(print resp)
(flush)
)
如果您使用 println
而不是打印
,则必须这样。
Also, the flushes aren't necessary if you use println
instead of print
.
推荐答案
我什么也不知道clojure,但这听起来像一个缓冲区不能刷新的情况。找出如何刷完标准后打印。 println函数可能在每行结束时刷新。尝试:
I know nothing of clojure but this sounds like a case of buffers not getting flushed. Figure out how to flush standard out after the print. The println function probably flushes at the end of each line. Try:
(defn goo []
(print "echo> ")
(flush )
(def resp (read-line))
(print resp)
)
这篇关于Clojure - 副作用发生乱序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!