How to do an inverse `range`, i.e. create a compact range based on a set of numbers?

前端 未结 6 639
忘了有多久
忘了有多久 2021-02-06 11:35

Python has a range method, which allows for stuff like:

>>> range(1, 6)
[1, 2, 3, 4, 5]

What I’m looking for is kind of t

6条回答
  •  盖世英雄少女心
    2021-02-06 11:47

    I thought you might like my generalised clojure solution.

    (def r [1 2 3 9 10])
    
    (defn successive? [a b]
      (= a (dec b)))
    
    (defn break-on [pred s]
      (reduce (fn [memo n]
                (if (empty? memo)
                  [[n]]
                  (if (pred (last (last memo)) n)
                    (conj (vec (butlast memo))
                          (conj (last memo) n))
                    (conj memo [n]))))
              []
              s))
    
    (break-on successive? r)
    

提交回复
热议问题