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.
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With