[Haskell-cafe] Read instance for constructors?

S D Swierstra doaitse at swierstra.net
Mon Mar 10 15:40:54 UTC 2014


Why not use:

http://hackage.haskell.org/package/ChristmasTree

which supports even infix constructors and runs in linear time,

 Doaitse Swierstra


On 10 Mar 2014, at 14:11 , Semen Trygubenko / Семен Тригубенко <semen at trygub.com> wrote:

> Dear Haskell-cafe,
> 
> When deriving (Read), only values can be read in.
> If one wants to be able to read in constructors, too, is there an easy way out?
> E.g., the code below works, but the extra book-keeping
> 
> f "A" = A
> ...
> 
> is unpleasant — perhaps there's a simpler solution?
> 
> {-# LANGUAGE FlexibleInstances #-}
> 
> data D = A Int
>       | B Int
>        deriving (Show,Read)
> 
> instance Read (Int -> D) where
>    readsPrec = \_ s -> [(f s,"")]
>                  where f "A"       = A
>                        f "B"       = B
>                        f x         = error $ "Invalid constructor " ++ x 
> 
> main = do let x = read "A 1" :: D
>          print x
>          let g s = read s :: (Int -> D)
>          print $ g "B" 2
>          print $ g "C" 3
> 
> Many thanks in advance,
> Semen
> 
> 
> 
> -- 
> Семен Тригубенко http://trygub.com
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list