具有类型Num([Char] - > t)的奇怪哈斯克尔表达式=> Ť [英] Strange Haskell expression with type Num ([Char] -> t) => t
问题描述
在GHCi中进行一些练习时,我键入并获得以下内容:
ghci> (11)
<互动>:187:1:
由于使用'it'而导致的(Num([Char] - > a0)
在一个交互式GHCi命令的脚本中:打印它
这是一个错误,howeve如果我问GHCi表达式的类型,它不会给出任何错误:
ghci> :type(1one)
(1one):: Num([Char] - > t)=> t
(1one)
为什么这个表达式给出了一个错误,但是GHCi告诉它它的类型很好?
Num([Char] - > t)=>的含义是什么? t
?
谢谢。 > Haskell报救! (引用第6.4.1节)
整型文字表示函数
fromInteger
对Integer类型的适当值的应用。 / p>
fromInteger
有类型:
Prelude> :t fromInteger
fromInteger :: Num a =>整数 - > a
因此 1
实际上是语法糖 fromInteger(1 :: Integer)
。然后,您的表达是:
fromInteger 1one
可以写成:
(fromInteger 1)一个
现在,来自整数的产生一个数字(也就是类型的值,它是
Num
的一个实例,就像它的类型告诉我们的那样)。在你的表达式中,这个数字应用于 [Char]
(字符串one
)。 GHC正确地将这两条信息结合起来,推断出您的表达式具有以下类型:
Num([Char] - > t) => t
也就是(未指定类型 t
)将一个也是 Num
的函数应用于 [Char]
。原则上这是一种有效的类型。唯一的问题是,对于 [Char] - >没有
Num
的实例。
$ b
PS:正如Sibi和Ørjan指出的那样,在GHC 7.10和更高版本中,如果启用 FlexibleContexts
GHC扩展,只会看到问题中提到的错误;否则类型检查器会反而抱怨类约束中有固定的类型和类型构造函数(即, Char
, []
和( - >)
)。
While doing some exercises in GHCi I typed and got the following>
ghci> (1 "one")
<interactive>:187:1:
No instance for (Num ([Char] -> a0)) arising from a use of ‘it’
In a stmt of an interactive GHCi command: print it
which is an error, howeve if I ask GHCi for the type of the expression it does not give any error:
ghci> :type (1 "one")
(1 "one") :: Num ([Char] -> t) => t
What is the meaning of (1 "one")
?
Why does this expression gives an error, but GHCi tells it is well typed?
What is the meaning of Num ([Char] -> t) => t
?
Thanks.
Haskell Report to the rescue! (Quoting section 6.4.1)
An integer literal represents the application of the function
fromInteger
to the appropriate value of type Integer.
fromInteger
has type:
Prelude> :t fromInteger
fromInteger :: Num a => Integer -> a
So 1
is actually syntax sugar for fromInteger (1 :: Integer)
. Your expression, then, is:
fromInteger 1 "one"
Which could be written as:
(fromInteger 1) "one"
Now, fromInteger
produces a number (that is, a value of a type which is an instance of Num
, as its type tells us). In your expression, this number is applied to a [Char]
(the string "one"
). GHC correctly combines these two pieces of information to deduce that your expression has type:
Num ([Char] -> t) => t
That is, it would be the result (of unspecified type t
) of applying a function which is also a Num
to a [Char]
. That is a valid type in principle. The only problem is that there is no instance of Num
for [Char] -> t
(that is, functions that take strings are not numbers, which is not surprising).
P.S.: As Sibi and Ørjan point out, in GHC 7.10 and later you will only see the error mentioned in the question if the FlexibleContexts
GHC extension is enabled; otherwise the type checker will instead complain about having fixed types and type constructors in the class constraint (that is, Char
, []
and (->)
).
这篇关于具有类型Num([Char] - > t)的奇怪哈斯克尔表达式=> Ť的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!