我创建了一个类似的类型 Maybe
data Defined a = Is a | Undefined
我做了个Show实话
instance Show a => Show (Defined a) where
show (Is a) = show a
show Undefined = "?"
Run Code Online (Sandbox Code Playgroud)
所以,我尝试实现该实例 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
Run Code Online (Sandbox Code Playgroud)
这是工作,但我不明白为什么.为什么这里没有无限循环:
otherwise -> map (\(a,b) -> (Is a,b)) $ readsPrec 0 s
Run Code Online (Sandbox Code Playgroud)
readsPrec 0 s尝试读取相同的字符串,如输入,不是吗?所以它必须otherwise阻止并形成无限循环.但代码确实有效.
readsPrec 0 s尝试读取相同的字符串,如输入,不是吗?
是的,但它不一样readsPrec!让我添加一些类型注释:
{-# 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
Run Code Online (Sandbox Code Playgroud)
请注意,我不能readsContent用readsDefined这里替换,它们是两个不同类型签名的不同函数.这与您的代码中的情况相同,只有,readsDefined并且readsContent是方法的两个(不同的)实例化readsPrec,即它们共享相同的名称但仍然具有不同的实现.