Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure NullPointerException error

I'm new in clojure and try to write simple function which get list of numbers and filter only even numbers.

I want to do it witout filter or even?, only pure clojure

(defn my-even [ilist]
   (if
    (= (mod (first ilist) 2) 0)
    (concat (list (first ilist)) (my-even (rest ilist)))
    (my-even (rest ilist))
   )
)

I try to run it:

(my-even '(1,2,3,4,5))

But get error:

#<CompilerException java.lang.NullPointerException (NO_SOURCE_FILE:0)>

What's wrong?

Thank you.

like image 965
0xAX Avatar asked Mar 02 '26 10:03

0xAX


1 Answers

As Jonas said, you do not have a base case; in addition to that it is not idiomatic Clojure (or any other Lisp) to put parens on separate lines, also keep the if's predicate on the same line.

With destructuring it is a bit more readable:

(defn my-even? [coll]
  (if-let [[first & rest] coll]
    (if (= (mod first 2) 0)
      (cons first (my-even? rest))
      (my-even? rest))))
like image 106
Hamza Yerlikaya Avatar answered Mar 05 '26 13:03

Hamza Yerlikaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!