在 Clojure 中从键盘读取用户输入的 Lispy 方式?
我正在为 Clojure 程序编写一个函数,用于从键盘读取用户输入。如果用户输入无效的输入,则会警告用户,然后再次提示。当在像Python这样的语言中使用过程风格时,我会做这样的事情:
while 1:
value = input("What is your decision?")
if validated(value):
break
else:
print "That is not valid."
我在Clojure中能想到的最好的办法是:
(loop [value (do
(println "What is your decision?")
(read-line))]
(if (validated value)
value
(recur (do
(println "That is not valid.")
(println "What is your decision?")
(read-line)))))
这可行,但它是多余的,而且看起来很冗长。有没有更多的 Lispy/Clojurey 方法来做到这一点?
I am writing a function for my Clojure program that reads user input from the keyboard. If the user enters invalid input, the user is warned and then prompted again. When using a procedural style in a language like Python, I would do something like this:
while 1:
value = input("What is your decision?")
if validated(value):
break
else:
print "That is not valid."
The best I can come up with in Clojure is this:
(loop [value (do
(println "What is your decision?")
(read-line))]
(if (validated value)
value
(recur (do
(println "That is not valid.")
(println "What is your decision?")
(read-line)))))
This works, but it is redundant and seems verbose. Is there a more Lispy/Clojurey way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 println/read-line 组合分解为 get-line 函数:
这基本上就是您的 Python 版本所做的事情;不同之处在于 get-input 是 Python 内置的。
Factor out the println/read-line combo into a get-line function:
This is basically what your Python version does; the difference is that get-input is built-in for Python.