问题描述
我正在阅读的小节关于
在两个
- 您为实例定义的 readsPrec Read Color
-
Read [a]
我们在#2 <$中调用 readsPrec c $ c> readsPrecList 。
评估时
阅读[Red]:: [Color]
调用code> readsPrecList 。该函数会捕获前导方形paren,并用输入字符串Red调用 readsPrec 。您的函数将删除前三个字符,并使用值 Red 返回< readsPrecList ,并将输入字符串设置为] 。该函数检查下一个字符是一个方括号,并返回列表中的值 - 即 [Red] 。
为什么评估首先调用 readPrecList ?因为您要求阅读来创建一个列表。
为什么 readsPrecList 为类型颜色调用 readsPrec ?因为您要求阅读来创建颜色值的列表。
这是一个类型定向调度的例子 - readsPrec 调用的实例由所请求的值的类型决定。
I am reading the subsection of Real World Haskell Chapter 6 (typeclasses) about aninstance of Read for Color, which implements readsPrec function. I don't know what happens when I type (read "[Red]") :: [Color] in GHCi, getting a [Red] result.
For simplicity, I changed this implementation of the function a little, as shown below:
instance Read Color where readsPrec _ value = [(Red, drop (length "Red") value)]
Now, my confusion is: in GHCi, we can use the above as follows:
*Main> let readsPrec 2 "Red]" = [(Red, drop (length "Red") "Red]")] *Main> readsPrec 2 "Red]" [(Red,"]")]
Why readsPrec _ value = [(Red, drop (length "Red") value)] return [Red] when executing (read "[Red]") :: [Color]?
There is an interaction going on between two instances of readsPrec:
- the readsPrec you defined for instance Read Color
- the readsPrec defined by the Prelude for instance Read [a]
Let's call the readsPrec in #2 readsPrecList.
When evaluating
read "[Red]" :: [Color]
what first happens is the readsPrecList is called. That function gobbles up the leading square paren and calls your readsPrec with the input string "Red]". Your function drops the first three characters and returns back to readsPrecList with the value Red and input string set to "]". That function checks that the next character is a closing square bracket and returns back your value in a list - i.e. [Red].
Why does evaluation begin with a call to readPrecList? Because you are asking read to create a list of something.
Why does readsPrecList call the readsPrec for the type Color? Because you asked read to create a list of Color values.
This is an example of type-directed dispatch - the instance of readsPrec called is determined by the type of the value being requested.
这篇关于在ghci下执行``(读取[Red]"):: [Color]`时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!