Skip to content

Instantly share code, notes, and snippets.

@willtim
Created April 28, 2014 19:41
Show Gist options
  • Save willtim/11382009 to your computer and use it in GitHub Desktop.
Save willtim/11382009 to your computer and use it in GitHub Desktop.
Split a string up by occurrences of a substring
import Control.Arrow (second)
import qualified Data.List as L
splitOn :: Eq a => [a] -> [a] -> [[a]]
splitOn sep = L.unfoldr f
where
f [] = Nothing
f xs = Just $ second (drop l) $ breakList (L.isPrefixOf sep) xs
l = length sep
breakList :: ([a] -> Bool) -> [a] -> ([a], [a])
breakList p = para f ([], [])
where
f x ((ys, zs), xs) | p (x:xs) = ([], x:xs)
| otherwise = (x:ys, zs)
-- | list paramorphism, it should be in the standard library
para :: (a -> (b, [a]) -> b) -> b -> [a] -> b
para f z [] = z
para f z (x:xs) = f x (para f z xs, xs)
-- > splitOn "bar" "foobarbazbar"
-- > ["foo","baz"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment