Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure extracting value from map based on prioritized logic

I have a function that wants to pull a value out of a map based on a prioritized order. Currently I'm doing it as a nested if structure which is horrible. I have to believe there is a better way.

While this works is there a better way?

(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)
                         )
                     )
                 )
              )
          )
    )
)
like image 650
Y. Adam Martin Avatar asked Feb 20 '12 15:02

Y. Adam Martin


2 Answers

(some relatives [:self :north :west :east :south])
like image 64
Justin Kramer Avatar answered Oct 02 '22 21:10

Justin Kramer


What about:

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

Sample run:

user=> (filter-relatives {:a 1 :b 2 :c 3} [:z :b :a])                                                               
2
like image 33
skuro Avatar answered Oct 02 '22 22:10

skuro