函数不返回 (Clojure)

Function not returning (Clojure)

我是 clojure 的新手,我的函数 elligble voters 没有返回向量,我哪里出错了。

(def human-db
  [
   {:name "Kanishk" :age 28 :sex "male"}
   {:name "Kanishk1" :age 29 :sex "male"}
   {:name "Kanishk2" :age 0 :sex "female"}
   {:name "Kanishk3" :age 1 :sex "male"}
   {:name "Kanishk4" :age 3 :sex "female"}
   {:name "Kanishk5" :age 3 :sex "male"}
   {:name "Kanishk6" :age 3 :sex "female"}
   {:name "Kanishk7" :age 3 :sex "male"}
   {:name "Kanishk8" :age 3 :sex "female"}])


(defn elligble-voters
  [human-db]
  (reduce (fn
            [new-map map]
            (if (> (:age map) 18)
              (conj new-map map)))  [] human-db))
(elligble-voters human-db)

The problem is with your if expression - there is no else clause, so it is returning nil when the voter is aged less than 18.

human-db中的最后一项是3岁,所以ifreturnsnil,从而减少returnsnil

这个有效:

(defn elligble-voters [human-db]
  (reduce (fn [new-map map]
            (if (> (:age map) 18)
              (conj new-map map)
              new-map)) ;; <-- Added `new-map` here
          []
          human-db))

表达相同功能的更简洁的方式是这样的:

(filter (fn [{:keys [age]}] (> age 18)) human-db)

reduce 如果能够执行您想要的操作,请使用更适合过滤集合的内容。

filter

clojure.core/filter ([pred] [pred coll])

Returns a lazy sequence of the items in coll for which (pred item) returns logical true. pred must be free of side-effects. Returns a transducer when no collection is provided.


(defn elligble-voters [human-db]
  (filter #(> (:age %) 18) human-db))

#(> (:age %) 18)是匿名函数的shorthand,相当于

(fn [x] 
  (> (:age x) 18))