看一下以下片段:
Prelude> import Data.Word
Prelude> data Foo = Foo Word8 deriving Show
Prelude> Foo 4
Foo 4
Prelude> Foo 44
Foo 44
Prelude> Foo 444
Foo 188
Run Code Online (Sandbox Code Playgroud)
我有点惊讶444被隐含地转换为188,就像在不安全的C中一样.它看起来很容易出错.在Haskell中安全处理此类转换的惯用方法是什么?
UPDATE
看起来这只是文字的多态行为,现代编译器对此提出警告.最重要的是类型系统不允许这种隐式截断.Foo (444 :: Int)生成类型不匹配,因此如果仅在运行时知道值,则这是完全安全的.
最近向GHC发出警告,要求召集此类案件.使用GHC 7.8.3,我看到:
Prelude Data.Word> Foo 444
<interactive>:7:5: Warning:
Literal 444 is out of the Word8 range 0..255
Foo 188
Prelude Data.Word>
Run Code Online (Sandbox Code Playgroud)
编译时:
$ ghc so.hs
[1 of 1] Compiling Main ( so.hs, so.o )
so.hs:5:19: Warning: Literal 444 is out of the Word8 range 0..255
Run Code Online (Sandbox Code Playgroud)
因此惯用的解决方案是使用最流行的编译器的最新版本.
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |