Skip to content

Instantly share code, notes, and snippets.

@jamiltron jamiltron/pack.clj
Created Jul 14, 2011

Embed
What would you like to do?
Pack a Sequence
; Write a function which packs consecutive duplicates into a list
; (pack [1 1 2 1 1 1 3 3]) => '((1 1) (2) (1 1 1) (3 3)))
; (pack [[1 2] [1 2] [3 4]]) => '(([1 2] [1 2]) ([3 4])))
(defn pack [n]
(letfn [(pack-iter [seen col curr out]
(cond
(empty? curr) (reverse (cons col out))
(= seen (first curr)) (pack-iter seen (cons (first curr) col) (rest curr) out)
:else (pack-iter (first curr) '() curr (cons col out))))]
(pack-iter (first n) '() n '())))
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.