Search code examples
if-statementclojureperfect-numbers

if always returning nil in Clojure


I am trying to write a program that checks if a number is perfect or not using clojure. I am very new to Clojure or any other functional programming language.

When I remove the if statement on the 5th line it works fine. But I need to check if i divides the number or not. And that is my problem. Please check my function below and tell me why its returning nil. no matter what I change keeps returning nil.

And if any one can go line by line and explain what each line is doing that would help too. Thanks

(defn perfect [number]
   (loop [i 1 sum 0]
     (if (< i number)
       (recur (+ i 1)
              (if (= (mod number i) 0)
                (+ sum i)))
                sum)))

Solution

  • if always has two branches. If you only provide the code for one branch, the other simply returns nil. You need to provide some value for the loop to return in the case that the recur branch is not taken.

    To be clear, despite your title the if inside the recur is not the issue here, it's the if outside the recur returning nil. And we don't have statements in clojure, if is an expression, just like everything else.