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 ..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.
@p-himik Oh thats actually a better approach lol
Thanks
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.