Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell split string on last occurence

Is there any way I can split String in Haskell on the last occurrence of given character into 2 lists? For example I want to split list "a b c d e" on space into ("a b c d", "e"). Thank you for answers.

like image 253
rainmaker Avatar asked Jun 17 '26 02:06

rainmaker


1 Answers

I'm not sure why the solutions suggested are so complicated. Only one two traversals are needed:

splitLast :: Eq a => a -> [a] -> Either [a] ([a],[a])
splitLast c' = foldr go (Left [])
    where
        go c (Right (f,b)) = Right (c:f,b)
        go c (Left s) | c' == c = Right ([],s)
                      | otherwise = Left (c:s)

Note this is total and clearly signifies its failure. When a split is not possible (because the character specified wasn't in the string) it returns a Left with the original list. Otherwise, it returns a Right with the two components.

ghci> splitLast ' ' "hello beautiful world"
Right ("hello beautiful","world")
ghci> splitLast ' ' "nospaceshere!"
Left "nospaceshere!"
like image 130
Alec Avatar answered Jun 19 '26 18:06

Alec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!