ghc
如果整数文字超出给定类型的范围,则最新版本的会警告您。例如:
$ ghci
>>> let x = 330492039485 :: Data.Word.Word8
<interactive>:2:9: Warning:
Literal 330492039485 is out of the GHC.Word.Word8 range 0..255
但是,ghc
不会警告Data.Word
类型为负数的数字文字。相反,它会下溢(根据文档,有意地):
>>> let x = -1 :: Data.Word.Word8
>>> x
255
是否有任何类型的警告会否定文字,或者有什么方法可以创建自己的自定义警告类型?
默认情况下,像这样的文字-1
会减至negate (fromInteger 1)
。但是,有一种语言扩展NegativeLiterals
使它fromInteger (-1)
代替糖。如果启用,你做得到一个警告:
Prelude> :m +Data.Word
Prelude Data.Word> :set -W
Prelude Data.Word> :set -XNegativeLiterals
Prelude Data.Word> -1 :: Word
<interactive>:74:1: Warning:
Literal -1 is out of the Word range 0..18446744073709551615
18446744073709551615
Prelude Data.Word>
另外,您可以使自己的类型重新定义negate
,但是可能只会得到运行时错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句