Skip to content

Instantly share code, notes, and snippets.

@jamiltron
Created July 14, 2011 03:46
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 jamiltron/1081904 to your computer and use it in GitHub Desktop.
Save jamiltron/1081904 to your computer and use it in GitHub Desktop.
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