How to create instance of Read for a datatype in haskell

后端 未结 1 1290
梦毁少年i
梦毁少年i 2020-12-17 16:11

So I have a data type

data SomeType a =
    Type a |
    Mix (SomeType a) (SomeType a)

This my show instance for SomeType



        
相关标签:
1条回答
  • 2020-12-17 16:52

    Here's an example based on the documentation which should be able to parse everything that show renders (assuming the type has a compatible Read instance defined), that is read . show should be more or less the identity:

    instance (Read a) => Read (SomeType a) where
        readsPrec d r = readMix r ++ readType r
          where
            readMix = readParen True $ \r -> do
                (v1, r'') <- readsPrec d r
                (v2, r')  <- readsPrec d r''
                return (Mix v1 v2, r')
    
            readType r = do
                (v, r') <- readsPrec d r
                return (Type v, r')
    

    Thus,

    > read "(3 4)" :: SomeType Int 
    (3 4)
    it :: SomeType Int
    

    But note, that for SomeType Char the default Show instance of Char surrounds the character with single quotes:

    > read "('a' ('b' 'c'))" :: SomeType Char
    ('a' ('b' 'c'))
    it :: SomeType Char
    

    hope this helps

    0 讨论(0)
提交回复
热议问题