beginners

Mtende Kuyokwa 2026-05-30T08:15:57.315149Z

I want to return only odd numbers in from a function and I made this heavinly functions

(defn return-odd [collection]
  (map
    (fn [x]
     (when (odd? x)x))
    collection)
  )

(return-odd (range 0 10))
and output is below. Is there a way to design a function to return nothing. not nil but nothing. I mean I do not want nils spread all over
(nil 1 nil 3 nil 5 ..

p-himik 2026-05-30T08:17:47.952109Z

You can use filter. And it's in general not a good idea to hard-code how you traverse over a simple collection (`map`, filter, etc.). In other words, I myself would not create return-odd and instead use (filter odd? collection) whenever that filtering is needed.

Mtende Kuyokwa 2026-05-30T08:24:32.321969Z

@p-himik Oh thats actually a better approach lol

Mtende Kuyokwa 2026-05-30T08:24:43.065019Z

Thanks

👍 1
seancorfield 2026-05-30T13:06:07.620939Z

And to clarify why you got the result you did: map applies a fn to each element of a collection and produces a new collection with the same number of elements. So you got:

(when (odd? 0) 0) (when (odd? 1) 1) (when (odd? 2) 2) ...
which is
nil 1 nil ...
whereas filter uses a predicate (like odd?) to reduce a collection of N elements to a potentially smaller collection of M elements (N >= M). In the case of filter, it applies the predicate and either keeps the original element or throws it away.