1

I'm writing a parser

And it's working as it is :

type Parser a = String -> Maybe (a ,String)

parseInt :: Parser Int
parseInt "" =  Nothing 
parseInt s = case reads s ::[(Int, String)] of 
            [(x, s)]-> Just(x, s)
            _ -> Nothing


parseChar :: Char -> Parser Char
parseChar a  str | a == head str = Just (a, tail str)
                 |  otherwise = Nothing

But i need too change type Parser a = String -> Maybe (a ,String)

to

data Parser a = Parser { runParser :: String -> Maybe (a , String ) }

As soon as I do, it every function i wrote do not compile anymore, what are the step to do this change, and, what is happening ?

2
  • do yourself a favor and use data Parser a = MkParser { runParser :: String -> Maybe (a , String ) } instead. it will be much less confusing. you can always remove the Mks if you have to, afterwards. Commented Oct 2, 2021 at 20:38
  • to use a parser, you get at its function via pattern matching, or by using runParser. read more about it by searching for "Haskell record syntax". Commented Oct 2, 2021 at 21:18

1 Answer 1

1

You will need to use the Parser data constructor and thus wrap the function into that data constructor, so:

parseInt :: Parser Int
parseInt = Parser f
  where f "" =  Nothing 
        f s = case reads s ::[(Int, String)] of 
                [(x, s)]-> Just(x, s)
                _ -> Nothing

parseChar :: Char -> Parser Char
parseChar a = Parser f
  where f str | a == head str = Just (a, tail str)
              |  otherwise = Nothing
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.