9

在 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

请注意,pure ()不要pure (+1)打印任何内容。

4

1 回答 1

12

如果您使用return而不是pure. 要找出要做什么,ghci 必须为给定的表达式选择一个类型。ghci 的默认规则是在没有其他约束的情况下,它会选择IO一个ApplicativeMonad实例。因此,它解释pure 1为 type 的表达式IO Integer。如果 1.有实例而 2.没有,则执行在提示符处输入的类型的表达式IO a并打印其结果。因此在提示符下输入会导致aShowa()pure 1

v <- return (1 :: Integer)
print v
return v

正在执行(以及it绑定到返回的魔法变量v)。For pure (),特殊情况适用,因为()被认为是无趣的,因此只return ()执行并it绑定到(), for pure (+1),返回一个函数Show,范围内没有函数的实例,因此不打印任何内容。然而,

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当然,后者独立于范围内的实例)。

于 2011-10-31T03:05:11.607 回答