不使用Clojure中的Filter函数过滤奇数



如何过滤奇数并将它们放入向量中?(出于教育目的,我知道一个更好的方法来使用过滤器函数)

我的尝试是:

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

预期输出:

;=> [1 3  5 7 9]

第二个问题:在(if)函数中,如何设置if条件为false,然后什么都不做?如果我让它为空,它会带来nil。我不想那样。

感谢您的宝贵时间。

有一种方法:

(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]))

您也可以使用loop/recur来模拟reduce函数的功能。

使用我最喜欢的模板项目构建。

loop版本:

(loop [numbers (range 10)
result  []]
(let [x (first numbers)]
(cond
(empty? numbers) result
(and (int? x) (odd? x)) (recur (rest numbers) (conj result x))
:else (recur (rest numbers) result))))

最新更新