Skip to content

Instantly share code, notes, and snippets.

@cgrand cgrand/rle.clj

forked from fogus/rle.clj
Created Mar 9, 2011
What would you like to do?
(defn mundane-pack
"Mundane recursive way to pack a sequence"
[[f & r :as S]]
(if (seq S)
(let [[packed tail] (split-with #{f} S)]
(if (seq tail)
(cons packed (pack tail))
(defn pack
"Tail-recursive way to pack a sequence"
(letfn [(pack* [[f & r :as S] acc]
(when (seq S)
(let [[packed tail] (split-with #{f} S)]
(if (seq tail)
(recur tail (conj acc packed))
(conj acc packed)))))]
(pack* coll [])))
(defn rle
"Run-length encode a sequence"
(map #(vector (count %) (first %))
(pack coll)))
(def S '[a a a a b c c a a d e e e e])
(pack S)
;=> [(a a a a) (b) (c c) (a a) (d) (e e e e)]
(rle S)
;=> ([4 a] [1 b] [2 c] [2 a] [1 d] [4 e])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.