Guest User

Untitled

a guest
Aug 15th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. Function using foldr is too eager
  2. groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
  3. groupBy' f = foldr step []
  4. where step x [] = [[x]]
  5. step x (xs:xss)
  6. | x `f` head xs = (x:xs):xss
  7. | otherwise = [x]:xs:xss
  8.  
  9. groupBy' f = foldr step []
  10. where step x xss = let (ys, yss) = step' x xss in (x:ys):yss
  11. step' x [] = ([], [])
  12. step' x (xs:xss) | f x (head xs) = (xs, xss)
  13. | otherwise = ([], xs:xss)
  14.  
  15. *Main> groupBy' (<) [1, 2, 3, 2, 3, 4, 1, undefined]
  16. [[1,2,3],[2,3,4],[1*** Exception: Prelude.undefined
  17.  
  18. groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
  19. groupBy' f [] = []
  20. groupBy' f [x] = [[x]]
  21. groupBy' f (x : xs)
  22. | x `f` head xs = (x : head l) : tail l
  23. | otherwise = [x] : l
  24. where
  25. l = groupBy' f xs
  26.  
  27. groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
  28. groupBy' f [] = []
  29. groupBy' f (x : xs) = hd : tl
  30. where
  31. (hd, tl) = go x xs
  32. go x [] = ([x], [])
  33. go x xs@(x' : xs')
  34. | x `f` x' = (x : hd', tl')
  35. | otherwise = ([x], hd' : tl')
  36. where
  37. (hd', tl') = go x' xs'
Add Comment
Please, Sign In to add comment