ghci是否适用于特殊情况? [英] ghci special case for Applicative?
问题描述
在ghci中:
λ> :t (pure 1)
(pure 1) :: (Applicative f, Num a) => f a
λ> show (pure 1)
<interactive>:1:1:
No instance for (Show (f0 a0))
arising from a use of `show'
Possible fix: add an instance declaration for (Show (f0 a0))
In the expression: show (pure 1)
In an equation for `it': it = show (pure 1)
λ> pure 1
1
这是否意味着ghci执行Applicative并显示结果,就像IO
一样?
Does this mean that ghci execute Applicative and displays the result, just like IO
?
请注意,pure ()
和pure (+1)
不会打印任何内容.
Note that pure ()
and pure (+1)
don't print anything.
推荐答案
如果使用return
而不是pure
,则会得到相同的行为.要找出要执行的操作,ghci必须为给定的表达式选择一种类型. ghci的默认规则是在没有其他约束的情况下,它为Applicative
或Monad
实例选择IO
.因此,它将pure 1
解释为类型IO Integer
的表达式.如果1.a
具有Show
实例,而2.a
不是()
,则在提示符下输入的类型为IO a
的表达式将被执行并打印其结果.因此,在提示符下输入pure 1
会导致
You get the same behaviour if you use return
instead of pure
. To find out what to do, ghci must choose a type for the given expression. ghci's defaulting rules are such that absent other constraints, it chooses IO
for an Applicative
or Monad
instance. Thus it interprets pure 1
as an expression of type IO Integer
. Expressions of type IO a
entered at the prompt are executed and their results are printed, if 1. a
has a Show
instance and 2. a
is not ()
. Thus entering pure 1
at the prompt results in
v <- return (1 :: Integer)
print v
return v
被执行(魔术变量it
绑定到返回的v
).对于pure ()
,特殊情况适用,因为认为()
不感兴趣,因此仅执行return ()
并将it
绑定到()
,对于pure (+1)
,将返回一个函数,没有Show
实例范围内的功能,因此不会打印任何内容.但是,
being executed (and the magic variable it
bound to the returned v
). For pure ()
, the special case applies since ()
is considered uninteresting, thus only return ()
is executed and it
bound to ()
, for pure (+1)
, a function is returned, there's no Show
instance for functions in scope, so nothing is printed. However,
Prelude Control.Applicative> :m +Text.Show.Functions
Prelude Control.Applicative Text.Show.Functions> pure (+1)
<function>
it :: Integer -> Integer
Prelude Control.Applicative Text.Show.Functions> it 3
4
it :: Integer
具有作用域中的函数的Show
实例,它会被打印出来(不是提供信息的内容),然后可以使用该函数(后者当然与作用域中的Show
实例无关).
with a Show
instance for functions in scope, it gets printed (not that it's informative), and the function can then be used (the latter is independent of a Show
instance being in scope, of course).
这篇关于ghci是否适用于特殊情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!