Skip to content

Instantly share code, notes, and snippets.

@ujihisa
Created October 9, 2011 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ujihisa/1274158 to your computer and use it in GitHub Desktop.
Save ujihisa/1274158 to your computer and use it in GitHub Desktop.
import qualified Text.Parsec as P
import Control.Applicative ((<$>), (<*>))
main = do
-- Ruby equivalent: "ab, d, ef,g".split(/, /) #=> ["ab", "d", "ef,g"]
print $ split ", " "ab, d, ef,g"
print $ split ", " "ab, d, ef,g" == ["ab", "d", "ef,g"]
print $ split2 ", " "ab, d, ef,g"
print $ split2 ", " "ab, d, ef,g" == ["ab", "d", "ef,g"]
split :: String -> String -> [String]
split b t = split' b "" t
where
split' b memo "" = [reverse memo]
split' b memo t@(th:tb)
| b == take (length b) t = (reverse memo) : split b (drop (length b) t)
| otherwise = split' b (th : memo) tb
split2 :: String -> String -> [String]
split2 b t = case P.parse (split' b) "split2" t of Right x -> x
where
split' b = anyUntil (P.string b) `P.sepBy` P.string b
anyUntil p = P.try (P.notFollowedBy p >> (:) <$> P.anyChar <*> anyUntil p)
P.<|> return ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment