Search code examples
clojure

Clojure returning simple true or false from a function


I am new to Clojure and i am having trouble with the basics of it. I am trying to write a simple if else program and use it in recursion but i am having trouble with the syntax. The code in Java is :

if(a > 0 && b >0){
   return true;
}else{
  return false;
}

The code in clojure should be :

(defn checkPositiveNumber 
    [x y]
    (if (and (> x 0) (> y 0))
            (do 
                (def val true)
            )
            (do 
                (def val false) 
    )
)

(println (checkPositiveNumber 2 3))

returns #'user/val instead of false. What am i doing wrong ? This function should return true or false as i will be using it to either terminate my recursion or to check further.

Edit: Thanks to Lee i was able to achieve the thing i asked... But my real purpose is :

if(a > 0 && b >0){
       System.out.println("Values are Positive");
       return true;
    }else{
      System.out.println("Some Values are Negative");
      return false;
    }

Solution

  • There is no analogue of return in clojure. Clojure function bodies are expressions so you need to organise your function to evaluate to true or false for each case.

    In this case you don't need to use if at all:

    (defn checkPositiveNumber [x y]
      (and (> x 0) (> y 0)))
    

    if you want to execute some side-effect in each branch you can use 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)))