ghci special case for Applicative?

瘦欲@ 提交于 2020-04-12 09:57:54

问题


In 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

Does this mean that ghci execute Applicative and displays the result, just like IO?

Note that pure () and pure (+1) don't print anything.


回答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

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

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).



来源:https://stackoverflow.com/questions/7949464/ghci-special-case-for-applicative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!