instance Read a, given a Parsec parser
Given any type a, for which there exists an parsecRead :: Parser a, the instance Read a can be defined really easily.
But I didn't find it in the Parsec docs. Maybe I wasn't looking hard enough.
{- This code is dedicated to the public domain. -}
import Text.ParserCombinators.Parsec
class ParsecRead a where
parsecRead :: Parser a
instance (ParsecRead a) => Read a where
readsPrec _ = either (const []) id . parse parsecRead' "" where
parsecRead' = do a <- parsecRead
rest <- getInput
return [(a, rest)]
It could be used like this:
data Foo = Foo
instance ParsecRead Foo where
parsecRead = string "foo" >> return Foo
-- instance Read Foo
Defining instance Read a requires GHC's -fallow-undecidable-instances, though.
Well, you could always just repeat the readsPrec definition for everything you want, but it seems to me that this should exist just because it's convenient and common enough.
- dtlin's blog
- Login to post comments
I like it.
Would you be interested in stating a copyright/license for it so I can include it in MissingH?
I'd be glad to. Can I just add a comment saying "This code is dedicated to the public domain", or do I need to do anything fancier?
That will probably be OK, though usually something like the BSD license accomplishes much the same but makes everyone feel a little more comfortable.