Files
notes/docs/lectures/compilers/04_functional_parsers.md
T
2026-10-04 15:24:17 +01:00

979 B

Functional Parsers

In our parser - there's a lot of repeated code and a lot of cases.

Types of scanner and parser are very similar

scanToken :: String  -> Maybe (Token, String)
parseTerm :: [Token] -> Maybe (AST,  [Token])
parseExp :: [Token]  -> Maybe (AST,  [Token])

general :: [c] -> Maybe (a, [c])
lessGeneral :: String -> Maybe (a, String)

--remember :t string :: [char]
-- [c] list of characters or tokens

Parser a :: String -> [(a, String)]
-- no maybe needed as failure is now returning an empty list
--The parser of type a, we can now define generic functions that operate on a given type => less repeated code
--This is an instance of a typeclass (monad yikes)

Do notation

Parser a = String -> [(a, String)]

symbol :: String -> Parser ()
-- no need to define result, as all it does it succeed or fail

exp :: Parser AST
parseParenthesis :: Parser AST
parseParenthesis = do symbol '('
					t <- exp
					symbol ')'
					return t