Home > other >  Couldn't match type Maybe ([a], a0)
Couldn't match type Maybe ([a], a0)

Time:10-12

I can't understand why I'm getting this error message:

Couldn't match typeMaybe ([a], a0)’
          with ‘String -> Maybe ([a1], String)’

My code :

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

parseMany :: Parse a -> Parse [a]
parseMany p str = case p str of 
                    Nothing -> Just ([], str)
                    Just (z, str') -> case parseMany (z str') of
                                    Just (c, str'') ->  Just ((z : c), show (str''))

CodePudding user response:

Using z str' makes no sense, z is an object of type a, not a function that can take a String parameter.

You can use the same base parser p to parse the next item:

parseMany :: Parse a -> Parse [a]
parseMany p str = case p str of 
    Nothing -> Just ([], str)
    Just (z, str') -> case parseMany p str' of
        Just (c, str'') ->  Just ((z : c), str'')
        Nothing -> Nothing

If we have a simple parser like:

myParser :: Parse Int
myParser ('a':xs) = Just (1, xs)
myParser _ = Nothing

then it will parse a list of 'a's to:

ghci> parseMany myParser "aaaaaa"
Just ([1,1,1,1,1,1],"")
  • Related