user14635008
user14635008

Reputation:

Parse letter or number with Parsec

I am trying to write a parser for strings such as x, A (i.e. single letters), 657 and 0 (i.e. integer positive numbers). Here is the code I wrote.

import Text.Parsec

data Expression = String String | Number Int

value = letter <|> many1 digit

However I get the following error.

Couldn't match type ‘[Char]’ with ‘Char’

Upvotes: 0

Views: 562

Answers (1)

radrow
radrow

Reputation: 7129

letter parses just a single letter and returns a Char. You want to parse a String, namely [Char] (it's the same thing), so I guess you want to parse many letter?

But if you want to parse just a single letter as a String you can take advantage of the fact that Parsec _ _ has a Functor instance in order to map over its result and pack it in a list:

value :: Parsec s u String 
value = fmap (:[]) letter <|> many1 digit

After the edit I guess you want to parse the Expression you have presented to us, so you will need some more fancy fmapping to wrap the results in proper constructors:

value :: Parsec s u Expression 
value = fmap (String . (:[])) letter
    <|> fmap (Number . read) (many1 digit)

Upvotes: 1

Related Questions