Skip to content

Instantly share code, notes, and snippets.

@Abhiroop
Created March 30, 2018 15:44
Show Gist options
  • Save Abhiroop/affa5134b0e3f306cb1b93b256bbfe64 to your computer and use it in GitHub Desktop.
Save Abhiroop/affa5134b0e3f306cb1b93b256bbfe64 to your computer and use it in GitHub Desktop.
;; Bear in mind this is a literal translation of the Haskell partitionBy.
;; This might not be the most idiomatic clojure.
(defn partition-by'' [f head tail]
(if (empty? tail)
(cons [head] tail)
(let [generator (partition-by'' f (first tail) (next tail))]
(if (= (f head) (f (first tail)))
(cons (cons head (first generator)) (next generator))
(cons [head] generator)))))
(defn partition-by' [f coll]
(lazy-seq
(when-let [s (seq coll)]
(partition-by'' f (first s) (next s)))))
;; Translated from
;; partitionBy :: Eq b => (a -> b) -> [a] -> [[a]]
;; partitionBy f [] = []
;; partitionBy f [x] = [[x]]
;; partitionBy f l = partitionBy' f (head l) (tail l)
;; partitionBy' _ x [xs] = [x : [xs]]
;; partitionBy' f x xs@(x':_)
;; | (f x) == (f x') = (x : (head generator)) : (tail generator)
;; | otherwise = [x] : generator
;; where
;; generator = partitionBy' f (head xs) (tail xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment