在Haskell中读取实例

时间:2015-02-11 14:43:22

标签: haskell

我创建了一个类似于Maybe

的类型

data Defined a = Is a | Undefined

我做了Show实例

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

所以,我尝试实现实例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

这是工作,但我不明白为什么。为什么这里没有无限循环:

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

readsPrec 0 s尝试读取输入中的相同字符串,不是吗?所以它必须转到otherwise阻止并形成一个无限循环。但代码确实有效。

1 个答案:

答案 0 :(得分:6)

  

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

请注意,我无法在此处将readsContent替换为readsDefined,它们是具有不兼容类型签名的两个不同功能。这与您的代码中的情况相同,只有readsDefinedreadsContent都是readsPrec方法的(不同)实例,即它们共享相同的名称,但仍然有不同的实现。