简体   繁体   English

clojure:如何在if语句中使用recur

[英]clojure: how to use recur in if statement

Disclaimer: I'm learning clojure. 免责声明:我正在学习Clojure。

This is the simple example I'm trying to run: 这是我要运行的简单示例:

(ns ClojureTest.core)

(let [input (read-line)]
  ;if user input = "x"
  (if (= "x" input)
    ;stop accepting input
    (println "Exit")
    ;else output the input and continue accepting input
    (
      (println input)
      (recur)
    )
  )
)

Now I'm getting this error, which I guess makes sense, because I'm unfamiliar with syntax: 现在我遇到了这个错误,我认为这是有道理的,因为我不熟悉语法:

Exception in thread "main" java.lang.UnsupportedOperationException: Can only recur from tail position, compiling:(ClojureTest/core.clj:8:7)

How do I fix this? 我该如何解决?

Side questions: 附带问题:

  1. When I click "run" in eclipse (as I would do with Java) I get not only the console opened but this "REPL" window. 当我在Eclipse中单击“运行”时(就像我对Java所做的那样),不仅打开了控制台,而且看到了“ REPL”窗口。 Why is it necessary and what does it do? 为什么有必要,它有什么作用?
  2. When I click "run" it takes quite a few seconds to launch the app. 当我单击“运行”时,需要花费很长时间才能启动该应用程序。 Is there a way to make it faster? 有没有办法使其更快?
  3. When I need to edit the code and relaunch the app I'm getting this message: "The selection cannot be launched, and there are no recent launches". 当我需要编辑代码并重新启动应用程序时,我收到以下消息:“选择无法启动,并且没有近期启动”。 What is that and why wouldn't it let me relaunch my code? 那是什么,为什么它不让我重新启动代码? If I wait a while I can launch it again. 如果我稍等片刻,可以再次启动它。

In this particular case, you're missing a do in the "else" clause of the if : 在这种特殊情况下,你错过了一个do了的“其他”条款中if

(do
  (println input)
  (recur))

Without the do , you've got ((println input) (recur)) , which looks like a function call with the return value of (println input) being the function to call and (recur) being the argument expression and so, not in tail position. 如果没有do ,您将得到((println input) (recur)) ,它看起来像一个函数调用,其中(println input)的返回值是要调用的函数,而(recur)是参数表达式,因此,不是在尾巴位置。

(Clearly (println input) would return nil and attempting to call that as a function would throw a NullPointerException , but this is irrelevant here -- it would be a runtime error, whereas the recur -not-in-tail-position problem is detectable at compile time.) (很明显, (println input)将返回nil并尝试将其作为函数调用将抛出NullPointerException ,但这在此无关紧要-这将是运行时错误,而可检测到recur -not-in-tail-position问题在编译时。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM