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)
The problem is that your function is a sequence of two-clause if
-forms.
if
-form returns nil
.The quickest repair is, as WeGi suggested, to nest the if
s:
(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))