I have created a type similar to Maybe
data Defined a = Is a | Undefined
I made the Show instnance
instance Show a => Show (Defined a) where
show (Is a) = show a
show Undefined = "?"
So, I try to implement the instance Read
instance Read a => Read (Defined a) where
readsPrec _ s = case (take 1 s) of
"?" -> [(Undefined,tail s)]
otherwise -> map (\(a,b) -> (Is a,b)) $ readsPrec 0 s
That's work, but I can't understand why. Why there is no infinite loop here:
otherwise -> map (\(a,b) -> (Is a,b)) $ readsPrec 0 s
readsPrec 0 s try to read the same string such as in input, isn't it? So it have to go to otherwise block yet and form an infinite loop. But the code is really works.
ShowandReadinstances are shunned in Haskell:showshould produce valid Haskell code, so"?"won't do as a result. If what you're trying to do is just pretty printing, e.g. for ghci, then you should stay with theMaybecontainer and just use a suitable pretty-printing function.Maybecontainer because I made theEqinstance ofDefinedtype with differing behaviourEqinstance with differing behaviour? I wager that's an even worse idea (but if you properly hide theUndefinedconstructor, it might be ok). At any rate, you shouldn't let theshow (Is a)print out only theavalue, without ever mentioning it was wrapped in aDefined.(Nothing == Nothing)isTruein the implementation ofEqforMaybethat's not I want forDefinedtype, so I have to create my own type or overloadEqforMaybethat's even worse.Undefined == Undefinedto be false! At least not unlessUndefinedis really some kind of exceptional value that wouldn't ever appear in applications. (Yes, I know that analogously, for floating-point numbers IEEE754 specifiesNaN == NaNto be false, but that's truely a horrible hack that has caused lots of problems of its own.)