我正在阅读Real World Haskell Chapter 6 (typeclasses)关于实现Read
功能Color
readsPrec
实例的小节。我不知道当我在GHCi中输入(read "[Red]") :: [Color]
并获得[Red]
结果时会发生什么。
为简单起见,我稍微更改了函数的这个实现,如下所示:
instance Read Color where
readsPrec _ value = [(Red, drop (length "Red") value)]
现在,我的困惑是:在GHCi中,我们可以使用以下内容:
*Main> let readsPrec 2 "Red]" = [(Red, drop (length "Red") "Red]")]
*Main> readsPrec 2 "Red]"
[(Red,"]")]
为什么readsPrec _ value = [(Red, drop (length "Red") value)]
在执行[Red]
时会返回(read "[Red]") :: [Color]
?
答案 0 :(得分:4)
readsPrec
的两个实例之间存在交互:
readsPrec
instance Read Color
readsPrec
instance Read [a]
醇>
让我们拨打#readsPrec
中的readsPrecList
。
评估时
read "[Red]" :: [Color]
首先发生的是调用readsPrecList
。该函数吞噬了前导方块paren并使用输入字符串" Red]"调用readsPrec
。您的函数会删除前三个字符并返回readsPrecList
,其值为Red
,输入字符串设置为"]"。该函数检查下一个字符是否为结束方括号,并在列表中返回您的值 - 即[Red]
。
为什么评估从调用readPrecList
开始?因为您要求read
创建一个列表。
为什么readsPrecList
为类型readsPrec
调用Color
?因为您要求read
创建Color
值列表。
这是类型定向调度的示例 - 调用的readsPrec
实例由请求的值的类型决定。