在 Clojure 中从键盘读取用户输入的 Lispy 方式?

发布于 2024-10-04 13:57:46 字数 644 浏览 0 评论 0原文

我正在为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月亮邮递员 2024-10-11 13:57:46
(defn input []
   (println "What is your decision?")
   (if-let [v (valid? (read-line))]
      v
      (do
         (println "That is not valid")
         (recur)))
(defn input []
   (println "What is your decision?")
   (if-let [v (valid? (read-line))]
      v
      (do
         (println "That is not valid")
         (recur)))
樱花细雨 2024-10-11 13:57:46

将 println/read-line 组合分解为 get-line 函数:

(defn get-input [prompt]
  (println prompt)
  (read-line))

(defn get-validated-input []
  (loop [input (get-input "What is your decision?")]
    (if (valid? input)
      value
      (recur (get-input "That is not valid.\nWhat is your decision?")))))

这基本上就是您的 Python 版本所做的事情;不同之处在于 get-input 是 Python 内置的。

Factor out the println/read-line combo into a get-line function:

(defn get-input [prompt]
  (println prompt)
  (read-line))

(defn get-validated-input []
  (loop [input (get-input "What is your decision?")]
    (if (valid? input)
      value
      (recur (get-input "That is not valid.\nWhat is your decision?")))))

This is basically what your Python version does; the difference is that get-input is built-in for Python.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文