Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function using foldr is too eager
- groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
- groupBy' f = foldr step []
- where step x [] = [[x]]
- step x (xs:xss)
- | x `f` head xs = (x:xs):xss
- | otherwise = [x]:xs:xss
- groupBy' f = foldr step []
- where step x xss = let (ys, yss) = step' x xss in (x:ys):yss
- step' x [] = ([], [])
- step' x (xs:xss) | f x (head xs) = (xs, xss)
- | otherwise = ([], xs:xss)
- *Main> groupBy' (<) [1, 2, 3, 2, 3, 4, 1, undefined]
- [[1,2,3],[2,3,4],[1*** Exception: Prelude.undefined
- groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
- groupBy' f [] = []
- groupBy' f [x] = [[x]]
- groupBy' f (x : xs)
- | x `f` head xs = (x : head l) : tail l
- | otherwise = [x] : l
- where
- l = groupBy' f xs
- groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
- groupBy' f [] = []
- groupBy' f (x : xs) = hd : tl
- where
- (hd, tl) = go x xs
- go x [] = ([x], [])
- go x xs@(x' : xs')
- | x `f` x' = (x : hd', tl')
- | otherwise = ([x], hd' : tl')
- where
- (hd', tl') = go x' xs'
Add Comment
Please, Sign In to add comment