How to apply max to a list of values with predefined order in Clojure?
clojure
Solution
first define the ordering:
user> (def order '[Tier5 Tier10 Tier20 Tier30 Tier40 Tier50])
#'user/order
then we map the order onto something that can be sorted by creating a `map`
user> (def order-map (zipmap order (range)))
{Tier50 5, Tier40 4, Tier30 3, Tier20 2, Tier10 1, Tier5 0}
use the order-map to reduce the input if all you need is the max/min:
user> (reduce #(if (< (order-map %1) (order-map %2)) %1 %2)
'[Tier20 Tier10 Tier30])
Tier30
or if you need the full ordering then use the sort-by function, which is like the regular sort function except it gives you a chance to translate the input before comparison:
user> (sort-by (zipmap order (range)) '[Tier20 Tier10 Tier30])
(Tier10 Tier20 Tier30)
if you need to modify this map a lot and not re-sort it each time then use a `sorted-set-by` datastructure to store your inputs.
Problem
I need to apply the max operator to the following list ``` [Tier20 Tier10 Tier30] ``` And it should give me ``` Tier30 ``` The predefined ordered list (from low to high) is ``` [Tier5 Tier10 Tier20 Tier30 Tier40 Tier50] ``` What's the best way to achieve this in Clojure?