This works with keywords
(sort-by (comp :rank second) >
{:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20}})
This fails when it's a string
(sort-by (comp "rank" second) >
{:1 {:bar "something" "rank" 10} :2 {:bar "other" "rank" 20}})
Error message is "Execution error (ClassCastException) at java.util.TimSort/countRunAndMakeAscending (TimSort.java:355). java.lang.String incompatible with clojure.lang.IFn"
I take it the problem is that keywords can be a function but strings cannot be functions. What is the solution? I've tried playing around with get
without success.
comp
composes functions, so you'll need a function that can get the key by string:
user> (->> {:1 {:bar "something" "rank" 10} :2 {:bar "other" "rank" 20}}
(sort-by (comp #(get % "rank") second) >))
([:2 {:bar "other", "rank" 20}] [:1 {:bar "something", "rank" 10}])