Created
April 28, 2014 19:41
-
-
Save willtim/11382009 to your computer and use it in GitHub Desktop.
Split a string up by occurrences of a substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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