Skip to content

Instantly share code, notes, and snippets.

@rhwlo
Last active August 29, 2015 14:10
Show Gist options
  • Save rhwlo/d6bd6281b34330e37986 to your computer and use it in GitHub Desktop.
Save rhwlo/d6bd6281b34330e37986 to your computer and use it in GitHub Desktop.
break lists of lists on a list of delimiters
import Control.Applicative
-- delimTake takes until it either:
-- 1) reaches the nth item (as "take N")
-- 2) reaches an item containing a delimiter
delimTake :: (Eq a) => [a] -> Int -> [[a]] -> [[a]]
delimTake delimList n seq
| snd brokenTake == [] = naiveTake
| otherwise = (fst brokenTake) ++ [fst breakDelimItem]
where
naiveTake = take n seq
containsDelim = (\item -> or ((==) <$> delimList <*> item))
brokenTake = break containsDelim naiveTake
breakDelimItem = (break (\item -> elem item delimList) (head (snd brokenTake)))
testString = "hello; this is a test."
-- as a test:
main :: IO ()
main = do
print testString
print $ unwords (take 3 testWords)
print $ unwords (delimTake ";." 3 testWords)
where testWords = words testString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment