Search code examples
clojure

How can I subseq a sorted-map that uses tick LocalDate as a key?


It is possible to subseq a sorted collection in clojure like so:

(subseq (sorted-map-by clojure.core/< 1 :a 2 :b 3 :c) clojure.core/> 1)
=> ([2 :b] [3 :c])

If I use java.time.LocalDate as the key of the map using tick, then the subseq gives an error:

(require '[tick.alpha.api :as t :refer :all])
(let [m (sorted-map-by t/< 
                      (t/date "2021-01-01") :a
                      (t/date "2021-02-02") :b 
                      (t/date "2021-03-03") :c )]
  (clojure.core/subseq m t/< (t/date "2021-01-15")))
Error printing return value (IllegalArgumentException) at clojure.core/-cache-protocol-fn (core_deftype.clj:583).
No implementation of method: :< of protocol: #'tick.core/ITimeComparison found for class: java.lang.Integer

How can I subseq a sorted-map with java.time.LocalDate keys?


Solution

  • According to the docs of subseq, the test parameter of the function must be one of <, <=, > or >=.

    This is because it will be used to compare 0 to the result of the sorted collection's comparator function called on the elements. (Remember that < returns boolean values, however, t/< returns an integer.)

    So instead of

    (clojure.core/subseq m t/< (t/date "2021-01-15"))
    

    Write:

    (clojure.core/subseq m < (t/date "2021-01-15"))