Search code examples
filterclojure

Filter odd numbers without using filter function in Clojure


how can I filter odd numbers and put them into a vector? (For educational purposes I know a better way to use the filter function)

My attempt is:

(map
  (fn [x] (if (odd? x) (into [] cat x)))
  (range 0 10))

Expected output:

;=> [1 3  5 7 9]

Second question: In (if) function how can I set the when if condition is false then do exactly nothing. When if I leave it empty It brings nil. I don't want that.

Thank you for your time.


Solution

  • Here is one way to do it:

    (ns tst.demo.core
      (:use demo.core tupelo.core tupelo.test))
    
    (defn filter-odd
      [vals]
      (reduce
        (fn [cum item]
          ; Decide how to modify `cum` given the current item
          (if (odd? item)
            (conj cum item) ; if odd, append to cum result
            cum ; if even, leave cum result unchanged
            ))
        []    ; init value for `cum`
        vals ; sequence to reduce over
      ))
    
    (verify
      (is= (filter-odd (range 10))
        [1 3 5 7 9]))
    

    You could also use loop/recur to mimic the functionality of the reduce function.

    Built using my favorite template project.