Skip to content

Instantly share code, notes, and snippets.

@sdarlington
Last active August 29, 2015 14:04
Show Gist options
  • Save sdarlington/be76048bff124694769d to your computer and use it in GitHub Desktop.
Save sdarlington/be76048bff124694769d to your computer and use it in GitHub Desktop.
-- Haskell version of groupWhen
-- http://fssnip.net/6A
--
-- Seq.groupWhen isOdd [3;3;2;4;1;2] = seq [[3]; [3; 2; 4]; [1; 2]]
testList = [3, 3, 2, 4, 1, 2]
groupWhen f [] = []
groupWhen f (x:xs) = ( (x : takeWhile notf xs) : groupWhen f (dropWhile notf xs))
where notf x = not (f x)
isOdd x = mod x 2 == 1
main = print (groupWhen isOdd testList)
-- takeWhile/dropWhile are part of the language (possible in the standard library?) but
-- are pretty easy to create:
getStuff f [] = []
getStuff f (x:xs)
| f x = (x : getStuff f xs)
| otherwise = []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment