My Weblog

Blog about programming and math

Parsing with Applicative Functors

While reading Write Yourself a Scheme in 48 Hours, I thought of converting the monadic codes of parsing into applicative style. Learn you a Haskell for Great Good has excellent explanation about functors and applicative functors. Real World Haskell has excellent chapter on using applicative functors for parsing. Below is my attempt to convert the monadic codes of parsing into applicative style for Scheme parsing. On parsing note, see the excellent tutorial of Tony Morris and Albert Y. C. Lie.

import Control.Applicative hiding ( many , ( <|> )  )
import Text.ParserCombinators.Parsec hiding ( spaces )

symbol :: Parser Char
symbol =  oneOf "!$%&|+-*/:<=?>@^_~#"

spaces :: Parser ()
spaces = skipMany space 

parseString :: Parser LispVal
parseString = String <$> ( char '"' *>  x <*  char '"' ) where 
            x = many ( noneOf "\"" ) 
--This is not completely applicative style because I have to take the result for testing conditions.
parseAtom :: Parser LispVal
parseAtom = do 
       atom <-  ( : ) <$> ( letter <|> symbol ) <*> many ( letter <|> digit <|> symbol )
       return $ case atom of 
                "#t" -> Bool True
                "#f" -> Bool False
                _ -> Atom atom


parseNumber :: Parser LispVal
parseNumber = Number . read <$> many1 digit


parseList :: Parser LispVal
parseList = List <$> sepBy parseExpr space 

parseDottedList :: Parser LispVal
parseDottedList = DottedList <$> ( endBy parseExpr space ) <*> ( char '.' *> spaces *> parseExpr )


parseQuoted :: Parser LispVal
parseQuoted =  f  <$>   ( char '\'' *> parseExpr ) where 
              f x =   List [ Atom "quote" , x ] 

parseExpr :: Parser LispVal
parseExpr =  parseAtom 
         <|> parseString
         <|> parseNumber 
         <|> parseQuoted
         <|> ( char '(' *> spaces *> ( ( try parseList ) <|> parseDottedList ) <* spaces  <* char ')' )

Complete code on github ( Apart from applicative parsing every other code is from Scheme parsing tutorial ). If you have any comments or suggestion then please let me know.

Advertisements

January 18, 2013 - Posted by | Haskell, Programming | , , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: