在GHCi中,为什么我不能在REPL中显示`pure 1`?

Han*_*Sun 8 monads haskell functor ghci

我试图给一个提升值a.

?> :m Control.Applicative
?> let a = pure 1
Run Code Online (Sandbox Code Playgroud)

当我a在REPL中进行评估时,它会打印出来1.

?> a
1
Run Code Online (Sandbox Code Playgroud)

因此,我认为可能有showfor 的实现a,并试过这个:

?> show a
Run Code Online (Sandbox Code Playgroud)

但GHCi抛出一个错误:

<interactive>:70:1-4:
    No instance for (Show (f0 a0)) arising from a use of ‘show’
    The type variables ‘f0’, ‘a0’ are ambiguous
    Note: there are several potential instances:
      instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
        -- Defined in ‘GHC.Real’
      instance (Show a, Show b) => Show (a, b) -- Defined in ‘GHC.Show’
      instance (Show a, Show b, Show c) => Show (a, b, c)
        -- Defined in ‘GHC.Show’
      ...plus 32 others
    In the expression: show a
    In an equation for ‘it’: it = show a
Run Code Online (Sandbox Code Playgroud)

有没有人对此有任何想法?

chi*_*chi 19

GHCI被拖欠Applicative f => fIO.当你这样做

?> a
1
Run Code Online (Sandbox Code Playgroud)

你实际上是在做一个IO Integer动作

?> let a = return 1
?> a
1
Run Code Online (Sandbox Code Playgroud)

GHCi默认打印操作的结果IO.因此1在结果行中.(相当令人困惑的是,这1不是作为一个动作a的运行的输出- 也不是后者的返回值.)aIO

GHCi使用复杂的启发式方法来处理用户输入.首先,它尝试show它,可能默认某些类型的类,如数字类.这在你的情况下失败了.当失败时,它会尝试查看输入是否为IO操作.在这种情况下,将运行操作,如果可以show编辑结果,则会打印该操作.

请注意,这种GHCi魔法只发生在顶层.当你尝试时show a,GHCi在整体上尝试它的魔法show a,而不是在a,所以同样的效果不会发生.