在ghci下执行``(读取[Red]"):: [Color]`时会发生什么? [英] what happens when executing `(read "[Red]") :: [Color]` under ghci?
问题描述
我正在阅读 Real World Haskell第6章(typeclasses)的小节关于 为简单起见,我稍微改变了这个函数的实现,如下所示: 现在,我的困惑是:在GHCi中,我们可以使用上面的代码如下: code> readsPrec_value = [(Red,drop(lengthRed)value)] Read
对 Color
,它实现了 readsPrec
函数。我不知道当我在GHCi中输入(读[Red]):: [Color]
时发生了什么,得到一个 [Red] $ b
return
实例读取颜色其中
readsPrec _ value = [(Red,drop(长度为Red)value)]
$ c $
$ b pre> *主> let readsPrec 2Red= [(Red,drop(lengthRed)Red])]
* Main> readsPrec 2Red
[(Red,])]
[Red]
code>(读取[Red]):: [Color] ?
在两个 readsPrec
实例之间存在交互:
- 您为
实例定义的
readsPrec
Read Color -
实例定义的 readsPrec
Read [a]
我们在#2 <$中调用 readsPrec
c $ c> readsPrecList 。
评估时
阅读[Red]:: [Color]
调用code> readsPrecList 。该函数会捕获前导方形paren,并用输入字符串Red调用 readsPrec
。您的函数将删除前三个字符,并使用值 Red
返回< [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 forinstance Read Color
- the
readsPrec
defined by the Prelude forinstance 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]`时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!