Search code examples
clojure

clojure with multiple if statements


when I call the math() function, to "times", the REPL returns nil. when I use "add", it works fine... help!

(defn math [opr x y ]
    (if(= opr "times")
        (* x y)
    )
    (if(= opr "add")
        (+ x y)
    )
)
(math "times" 8 8)

Solution

  • The problem is that your function is a sequence of two-clause if-forms.

    • Clojure performs the elements of the sequence in turn, returning the result of the last.
    • If the condition fails, a two-clause if-form returns nil.

    The quickest repair is, as WeGi suggested, to nest the ifs:

    (defn math [opr x y]
      (if (= opr "times")
        (* x y)
        (if (= opr "add")
          (+ x y))))
    

    However, there are better ways:

    (defn math [opr x y]
      (case opr
        "add" (+ x y)
        "times" (* x y)))
    

    ... and, leaving C / Java idioms behind, ...

    (defn math [opr x y]
      ((case opr
         "add" +
         "times" *)
       x y))
    

    ... or ...

    (defn math [opr x y]
      (({"add" +, "times" *} opr) x y))