[英]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: 附带问题:
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.