具有多个if语句的clojure

jes*_*tan 3 clojure

当我调用math()函数时,"times",REPL返回nil.当我使用"添加"时,它工作得很好......帮助!

(defn math [opr x y ]
    (if(= opr "times")
        (* x y)
    )
    (if(= opr "add")
        (+ x y)
    )
)
(math "times" 8 8)
Run Code Online (Sandbox Code Playgroud)

Thu*_*ail 13

问题是,你的函数是一个序列两个条款if-forms.

  • Clojure依次执行序列的元素,返回最后的结果.
  • 如果条件失败,则if返回双子句-form nil.

正如WeGi建议的那样,最快的修复是嵌套ifs:

(defn math [opr x y]
  (if (= opr "times")
    (* x y)
    (if (= opr "add")
      (+ x y))))
Run Code Online (Sandbox Code Playgroud)

但是,还有更好的方法:

(defn math [opr x y]
  (case opr
    "add" (+ x y)
    "times" (* x y)))
Run Code Online (Sandbox Code Playgroud)

...而且,留下C/Java习语,......

(defn math [opr x y]
  ((case opr
     "add" +
     "times" *)
   x y))
Run Code Online (Sandbox Code Playgroud)

... 要么 ...

(defn math [opr x y]
  (({"add" +, "times" *} opr) x y))
Run Code Online (Sandbox Code Playgroud)


oni*_*nit 9

我喜欢在多个条件下使用cond语句.

;; Will return nil if the cond statement fails all the predicates
(defn math [opr x y ]
  (cond (= opr "times") (* x y)
        (= opr "add") (+ x y)))
Run Code Online (Sandbox Code Playgroud)

WeGi是正确的,因为Clojure将始终返回函数中的最后一个语句.


Chr*_*evo 5

当所有谓词都具有相同的结构时,condp 会起作用:

(defn my-calc
  [operator x y]
    (condp = operator
      "times" (* x y)
      "plus" (+ x y))) 

=> (var user/my-calc)
(my-calc "times" 2 3)
=> 6
(my-calc "plus" 2 3)
=> 5
Run Code Online (Sandbox Code Playgroud)