我是 Clojure 的新手,我在使用它的基础知识方面遇到了麻烦。我正在尝试编写一个简单的 if else 程序并在递归中使用它,但我遇到了语法问题。 Java中的代码是:
if(a > 0 && b >0){
return true;
}else{
return false;
}
clojure 中的代码应该是:
(defn checkPositiveNumber
[x y]
(if (and (> x 0) (> y 0))
(do
(def val true)
)
(do
(def val false)
)
)
(println (checkPositiveNumber 2 3))
返回 #'user/val
而不是 false。
我究竟做错了什么 ?这个函数应该返回 true 或 false,因为我将使用它来终止我的递归或进一步检查。
编辑: 多亏了李,我才得以实现我所要求的……但我的真正目的是:
if(a > 0 && b >0){
System.out.println("Values are Positive");
return true;
}else{
System.out.println("Some Values are Negative");
return false;
}
最佳答案
clojure 中没有return
的类似物。 Clojure 函数体是表达式,因此您需要组织函数以针对每种情况评估为 true
或 false
。
在这种情况下,您根本不需要使用 if
:
(defn checkPositiveNumber [x y]
(and (> x 0) (> y 0)))
如果你想在每个分支中执行一些副作用,你可以使用do
:
(defn checkPositiveNumber [x y]
(if (and (> x 0) (> y 0)))
(do
(println "x and y both positive")
true)
(do
(println "One of x or y non-positive")
false)))
关于Clojure 从函数返回简单的 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56365159/