Clojure:在向量中找到偶数

0 clojure

我来自Java背景,试图学习Clojure.由于最好的学习方式是通过实际编写一些代码,我采用了一个非常简单的例子,即在向量中找到偶数.下面是我写的代码:

`

(defn even-vector-2 [input]
  (def output [])
  (loop [x input]
    (if (not= (count x) 0)
      (do
        (if (= (mod (first x) 2) 0)
          (do
            (def output (conj output (first x)))))
        (recur (rest x)))))
  output)
Run Code Online (Sandbox Code Playgroud)

`

这段代码有效,但是我必须使用全局符号才能使它工作.我必须使用全局符号的原因是因为我想在每次在向量中找到偶数时改变符号的状态.let不允许我更改符号的值.有没有办法可以在不使用全局符号/原子的情况下实现.

Leo*_*hin 6

惯用的解决方案是直截了当的:

(filter even? [1 2 3])
; -> (2)
Run Code Online (Sandbox Code Playgroud)

出于教育目的,使用loop/recur实现

(defn filter-even [v]
  (loop [r []
         [x & xs :as v] v]
    (if (seq v) ;; if current v is not empty
      (if (even? x)
        (recur (conj r x) xs) ;; bind r to r with x, bind v to rest
        (recur r xs)) ;; leave r as is
      r))) ;; terminate by not calling recur, return r
Run Code Online (Sandbox Code Playgroud)