Clojure基于优先逻辑从地图中提取值

时间:2012-02-20 15:14:30

标签: map filter clojure conditional

我有一个想要根据优先顺序从地图中提取值的函数。目前我正在将它作为一个嵌套的if结构,这是非常可怕的。我不得不相信有更好的方法。

虽然这样做有更好的方法吗?

(defn filter-relatives [relatives]
    (if(contains? relatives :self)
         (relatives :self)
             (if(contains? relatives :north)
                 (relatives :north)
                     (if(contains? relatives :west)
                         (relatives :west)
                         (if(contains? relatives :east)
                             (relatives :east)
                             (relatives :south)
                         )
                     )
                 )
              )
          )
    )
)

4 个答案:

答案 0 :(得分:9)

(some relatives [:self :north :west :east :south])

答案 1 :(得分:5)

怎么样:

(defn filter-relatives [relatives ordered-filters] 
    (first (filter identity (map relatives ordered-filters))))

示例运行:

user=> (filter-relatives {:a 1 :b 2 :c 3} [:z :b :a])                                                               
2

答案 2 :(得分:5)

如果nilfalse不属于可能的值,则其他答案都可以。如果是,你可以使用像

这样的东西
(if-let [e (some (partial find relatives)
                 [:self :north :west :east :south])]
  (val e)
  :no-key-found)

E.g。

(if-let [e (some (partial find relatives)
                 [:self :north :west :east :south])]
  (val e)
  :no-key-found)
; => false

(if-let [e (some (partial find {})
                 [:self :north :west :east :south])]
  (val e)
  :no-key-found)
; => :no-key-found

答案 3 :(得分:1)

(first (keep relatives [:self :north :west :east :south]))