我写了一个非常简单的 Haskell 程序:
main = print $ sum $ map read ["55", "99", "101"]
鉴于我过去的经验,我预计会得到一个“模棱两可的类型”错误,因为sum $ map read [...]
is的签名(Read a, Num a) => a
;Num
是一个类,因此本身不能实现Show
该类。但是,程序正确输出了“255”。如何print
确定产生输出的方法?(show
也能够产生没有错误的正确结果。)
我写了一个非常简单的 Haskell 程序:
main = print $ sum $ map read ["55", "99", "101"]
鉴于我过去的经验,我预计会得到一个“模棱两可的类型”错误,因为sum $ map read [...]
is的签名(Read a, Num a) => a
;Num
是一个类,因此本身不能实现Show
该类。但是,程序正确输出了“255”。如何print
确定产生输出的方法?(show
也能够产生没有错误的正确结果。)
如果您使用该-fwarn-type-defaults
选项,您将得到:
$ ghc -O2 -fwarn-type-defaults ddd.hs
[1 of 1] Compiling Main ( ddd.hs, ddd.o )
ddd.hs:2:8: Warning:
Defaulting the following constraint(s) to type ‘Integer’
(Show s0) arising from a use of ‘print’ at ddd.hs:2:8-12
(Read s0) arising from a use of ‘read’ at ddd.hs:2:26-29
(Num s0) arising from a use of ‘sum’ at ddd.hs:2:16-18
In the expression: print
In the expression: print $ sum $ map read ["55", "99", "101"]
In an equation for ‘main’:
main = print $ sum $ map read ["55", "99", "101"]
这解释了发生了什么。