Reputation: 988
I am trying to make a nested function that should be run recursively in Clojure in order to collect some information. I have seen some techniques such as fn, loop, doseq but I am not good with them for now.
First let me explain why I want to use a recursive funtion: I have a class and this class include 2 methods itself, these methods are namely getLeft() and getRight(), plus the return type of the methods are also a class. I do want simply traverse all getLeft and getRight methods in order to get the proper number from them.
Just to be clear, I put a schema:
My Main Class:
+-- getRight(): class - getLeft/getRight
++ getLeft(): class ---
+-- getLeft((): class - getLeft/getRight
+-- getRight(): class - getLeft/getRight
++ getRight() :class
+-- getLeft((): class - getLeft/getRight
I also made a function called "loopingP" but when I add this func to my another function, it gives an error. Error: NullPointerException org.mtrcclojure.demo/loopingP (NO_SOURCE_FILE:4)
(defn loopingP [points]
(if (= (getKind points) 5)
( (loopingP (getRight points)) (loopingP (getLeft points)))
(if (= (getKind points) 3) (println "Yep"))))
How can I properly use a nested function in Clojure for my purpose? Thanks in advance!
Solution is: putting a []
(defn loopingP [points]
(if (= (getKind points) 5)
[ (loopingP (getRight points)) (loopingP (getLeft points))]
(if (= (getKind points) 3) (println "Yep"))))
Upvotes: 0
Views: 1083
Reputation: 20194
You have an extraneous set of parenthesis around your recursion case - perhaps you meant to group the getRight and getLeft calls into a pair? the base case always returns nil (either from the false branch of the if, or from the println) so the leftmost recursion gets applied, and thus you call nil as a function (leading to a NullPointerException).
Upvotes: 1