Is there a standard way to split a string in Haskell?
lines
and words
work great from splitting on a space or newline, but surely there is
I started learning Haskell yesterday, so correct me if I'm wrong but:
split :: Eq a => a -> [a] -> [[a]]
split x y = func x y [[]]
where
func x [] z = reverse $ map (reverse) z
func x (y:ys) (z:zs) = if y==x then
func x ys ([]:(z:zs))
else
func x ys ((y:z):zs)
gives:
*Main> split ' ' "this is a test"
["this","is","a","test"]
or maybe you wanted
*Main> splitWithStr " and " "this and is and a and test"
["this","is","a","test"]
which would be:
splitWithStr :: Eq a => [a] -> [a] -> [[a]]
splitWithStr x y = func x y [[]]
where
func x [] z = reverse $ map (reverse) z
func x (y:ys) (z:zs) = if (take (length x) (y:ys)) == x then
func x (drop (length x) (y:ys)) ([]:(z:zs))
else
func x ys ((y:z):zs)