Reading an instance in Haskell

I created a type similar to Maybe

data Defined a = Is a | Undefined

I did Showinstnance

instance Show a => Show (Defined a) where
    show (Is a) = show a
    show Undefined = "?"

So I'm trying to implement an 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

This works, but I can’t understand why. Why there is no endless loop:

otherwise -> map (\(a,b) -> (Is a,b)) $ readsPrec 0 s

readsPrec 0 stry reading the same line as the input, right? Therefore, it must go even before the block otherwiseand form an infinite loop. But the code does work.

+4
source share
1 answer

readsPrec 0 s try reading the same line as the input, right?

Yes, but it’s not the same readsPrec! Let me add some annotations like:

{-# LANGUAGE ScopedTypeVariables #-}

instance Read a => Read (Defined a) where
  readsPrec _ = readsDefined

readsDefined :: forall a . Read a => String -> ReadS (Defined a)
readsDefined s = case (take 1 s) of
                    "?" -> [(Undefined,tail s)]
                    otherwise -> map (\(a,b) -> (Is a,b)) $ readsContent s
 where readsContent :: String -> ReadS a
       readsContent = readsPrec 0

: readsContent readsDefined , . , , readsDefined readsContent - () readsPrec, .. , .

+6

All Articles