在 Clojure 中不使用过滤函数过滤奇数

问题描述 投票:0回答:1

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

我的尝试是:

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

预期产出:

;=> [1 3  5 7 9]

第二个问题:在(if)函数中,如果条件为假,我如何设置什么都不做。如果我把它留空它会带来零。我不想要那个。

谢谢你的时间。

filter clojure
1个回答
0
投票

这是一种方法:

(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
函数的功能。

使用我最喜欢的模板项目.

© www.soinside.com 2019 - 2024. All rights reserved.