在GHCi中,为什么我不能在REPL中显示“纯1"? [英] In GHCi, why can't I show `pure 1` in REPL?

查看:73
本文介绍了在GHCi中,为什么我不能在REPL中显示“纯1"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试为 a 分配提升的值.

I tried to assign a lifted value to a.

λ> :m Control.Applicative
λ> let a = pure 1

当我在REPL中评估 a 时,它将打印 1 .

When I evaluated a in REPL, it prints 1.

λ> a
1

因此,我认为可能为 a 实现了 show 的实现,并尝试了以下方法:

Therefore, I thought there may be an implementation of show for a, and tried this:

λ> show a

但是GHCi会引发错误:

But the GHCi throws an error:

<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

有人对此有任何想法吗?

Does anyone have any ideas about this?

推荐答案

GHCi默认使用 Applicative f =>f 转换为 IO .当你做

GHCi is defaulting the Applicative f => f to IO. When you do

λ> a
1

您实际上运行了 IO Integer 操作,例如

you actually run an IO Integer action such as

λ> let a = return 1
λ> a
1

默认情况下,

GHCi打印 IO 操作的结果.因此,结果行中的 1 .(非常令人困惑的是,此 1 不是 a 的值,也不是作为 IO 运行的 a 的输出操作-只是后者的返回值.)

GHCi by default prints the result of IO actions. Hence the 1 in the result line. (Quite confusingly, this 1 is not the value of a, nor the output of running a as an IO action -- just the returned value of the latter.)

GHCi使用复杂的启发式方法来处理用户输入.首先,它尝试显示它,可能默认使用一些类型类,例如数字类.在您的情况下,这将失败.如果失败,它将尝试查看输入是否为 IO 操作.在这种情况下,将运行该操作,如果可以对结果进行 show 显示,则将其打印出来.

GHCi uses a sophisticated heuristics to handle user input. First, it tries to show it, possibly defaulting some type classes like numeric ones. This fails in your case. When that fails, it tries to see if the input is an IO action. In such case, the action is run and, if the result can be showed, it is printed.

请注意,此GHCi魔术仅在最高级别发生.当您尝试显示 a 时,GHCi会在整个 showa 而不是 a 上尝试其魔力,因此不会发生相同的效果.

Note that this GHCi magic only happens at the top level. When you try to show a, GHCi tries its magic on the whole show a, not on a, so the same effect does not happen.

这篇关于在GHCi中,为什么我不能在REPL中显示“纯1"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆