Skip to content

Instantly share code, notes, and snippets.

@cgrand
Forked from fogus/rle.clj
Created March 9, 2011 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgrand/861908 to your computer and use it in GitHub Desktop.
Save cgrand/861908 to your computer and use it in GitHub Desktop.
(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))
[packed]))
[nil]))
(defn pack
"Tail-recursive way to pack a sequence"
[coll]
(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"
[coll]
(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