Writing parsers in Haskell is often part of introductory course.
It is as simple as defining
newtype Parser a = String -> Maybe (a, String)
which is just a function that takes String and returns a (which might be a token, statement or whatever) and the rest of String. Then you can wrap it in Maybe or Either for some basic error handling.
Afterwards you create instance of Functor, Aplicative, Monad and Alternative for Parser type. And you now can combine it to do anything you want.
e.g.
Code:
parseChar :: Char -> Parser Char
parseChar c = Parser fn
where
fn [] = Nothing
fn (x:xs)
| c == x = Just (c, xs)
| otherwise = Nothing
is parser which takes Char and returns Parser Char
Parser Char :: (String -> Maybe (Char, String))
Which is a function that will take String and return Char + rest of the String if the character is the first character that occurred in string, or Nothing otherwise.
Then you can combine those smaller parser using Alternative to automatically choose first possible parsing output
e.g.
Code:
parseWhitespace :: Parser Whitespace
parseWhitespace = charP ' ' <|> charP '\n' <|> charP '\t'
Will try to parse either space, newline or tab and will return Whitespace.
There is nice Tsoding video that goes more into detail.
But it's amazing how easy it is when done in functional style.
I assume it will be similiar in OCaml.