gpt4 book ai didi

haskell - 在 Haskell 中读取实例

转载 作者:行者123 更新时间:2023-12-03 09:49:06 25 4
gpt4 key购买 nike

我创建了一个类似于 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阻塞并形成无限循环。但代码确实有效。

最佳答案

readsPrec 0 s try to read the same string such as in input, isn't it?



是的,但不一样 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

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

关于haskell - 在 Haskell 中读取实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28457098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com