在ghci下执行`(读“[Red]”):: [Color]`时会发生什么?

时间:2014-12-12 11:05:47

标签: haskell typeclass

我正在阅读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]

1 个答案:

答案 0 :(得分:4)

readsPrec的两个实例之间存在交互:

  1. 您为readsPrec
  2. 定义的instance Read Color
  3. readsPrec
  4. 前奏所定义的instance Read [a]

    让我们拨打#readsPrec中的readsPrecList

    评估时

    read "[Red]" :: [Color]
    

    首先发生的是调用readsPrecList。该函数吞噬了前导方块paren并使用输入字符串" Red]"调用readsPrec。您的函数会删除前三个字符并返回readsPrecList,其值为Red,输入字符串设置为"]"。该函数检查下一个字符是否为结束方括号,并在列表中返回您的值 - 即[Red]

    为什么评估从调用readPrecList开始?因为您要求read创建一个列表。

    为什么readsPrecList为类型readsPrec调用Color?因为您要求read创建Color值列表。

    这是类型定向调度的示例 - 调用的readsPrec实例由请求的值的类型决定。