Created
March 30, 2018 15:40
-
-
Save Abhiroop/a1eea0442f58da33b1e3ad644e6f6dbe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) -- the recursion is delayed here by lazily creating a generator | |
| otherwise = [x] : generator | |
where | |
generator = partitionBy' f (head xs) (tail xs) | |
-- Tests | |
{- | |
infiniteSeq = (repeat 2) | |
l = [1,6,3,13] ++ infiniteSeq ++ [18,8] | |
let c = paritionBy (\x -> x `mod`5) l | |
> take 2 c | |
[[1,6],[3,13]] | |
> take 7 $ (c !! 2) -- the infinite sequence in between | |
[2,2,2,2,2,2,2] | |
-} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment