LYAH描述fromIntegral
为:
从它的类型签名我们看到它需要一个整数并将其转换为更一般的数字.当你希望积分和浮点类型很好地协同工作时,这很有用.
我不明白这个功能是如何工作的,或者为什么需要从解释器中学习它.
fromIntegral 4 + 3.2
7.2
4 + 3.2
7.2 -- seems to work just fine?!
fromIntegral 6
6
fromIntegral 6.2
-- raises an error
:t fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b -- does this mean it takes 1 arg or 2?
Run Code Online (Sandbox Code Playgroud)
Fre*_*Foo 11
fromIntegral :: (Integral a, Num b) => a -> b
Run Code Online (Sandbox Code Playgroud)
拿一个arg.本=>
应被理解为具有普遍定量的逻辑蕴涵:
所有类型的
a
和b
,如果
a
是的实例Integral
,并b
为实例Num
,然后
fromIntegral
可以采取a
和生产一个b
.
此函数将type a
(Integral
类型)的值转换为类型(b
更通用Num
类的实例).例如,您无法在不转换前者的情况下将整数添加1
到2
Haskell中的float :
Prelude> (1 :: Int) + (2 :: Float)
<interactive>:10:15:
Couldn't match expected type `Int' with actual type `Float'
In the second argument of `(+)', namely `(2 :: Float)'
In the expression: (1 :: Int) + (2 :: Float)
In an equation for `it': it = (1 :: Int) + (2 :: Float)
Prelude> fromIntegral (1 :: Int) + (2 :: Float)
3.0
Run Code Online (Sandbox Code Playgroud)