gpt4 book ai didi

haskell - 在 Haskell 中为自定义数据类型创建读取类型类的实例

转载 作者:行者123 更新时间:2023-12-03 11:56:52 25 4
gpt4 key购买 nike

我有一个自定义数据类型 Foo = Foo{ a :: Int, b :: Int}我正在尝试使 Foo 成为 read 的自定义实例。我已经有一个函数bar :: String -> Foo我试着这样做:

instance Read (Foo a b) where
read s = bar s

但是当我将文件加载到 GHCi 中进行测试时出现以下错误: Fraction.hs:11:1: read' is not a (visible) method of class Read'
有人可以告诉我问题是什么以及我如何实际实例化这种类型吗?

最佳答案

Read typeclass 未声明 read直接地;相反,它定义了 readsPrec ,它支持优先级(这在 read 涉及其他类型元素的复杂数据类型的值时很重要)。使用 deriving (Read) 时得到的定义看起来大致像

instance (Read a) => Read (Tree a) where

readsPrec d r = readParen (d > app_prec)
(\r -> [(Leaf m,t) |
("Leaf",s) <- lex r,
(m,t) <- readsPrec (app_prec+1) s]) r
++ readParen (d > up_prec)
(\r -> [(u:^:v,w) |
(u,s) <- readsPrec (up_prec+1) r,
(":^:",t) <- lex s,
(v,w) <- readsPrec (up_prec+1) t]) r
where app_prec = 10
up_prec = 5

(这显然适用于 Tree 数据类型,但类似的规则适用于其他用户定义的 ADT)。 (另外,上面是一个小小的谎言:GHC 实际上使用了不同的实现,但上面是你应该做的事情,除非你愿意在 GHC 内部挖掘。)
read定义为 readsPrecreadList ( Read 中的另一种方法,除了 Char 之外的所有类型都是默认的,它用于将 [Char] 作为字符串而不是 Char 的列表读取)。

如果标准推导不够,对于像你这样的类型,它只是 Int 的一个桶。 s 你可以忽略优先级参数。

顺便说一句, ReadShow比较慢;您可能需要考虑使用其他方式对您的数据进行 I/O。

关于haskell - 在 Haskell 中为自定义数据类型创建读取类型类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520940/

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