我不明白:来自整合 [英] I don't understand :t for fromIntegral
问题描述
LYAH 描述 fromIntegral
as:
从它的类型签名中我们可以看到它需要一个整数并将其转换为一个更一般的数字。
我不明白这个函数是如何工作的,或者,为什么需要与翻译人员一起玩耍。
fromInteral 4 + 3.2
7.2
4 + 3.2
7.2 - 似乎有效正好?!
fromInteral 6
6
fromInteral 6.2
- 引发错误
:t fromInteral
fromInteral ::(Integral a,Num b )=> a - > b - 这是否意味着需要1个参数或2个?
fromIntegral: :(积分a,数字b)=> a - > b
需要一个参数。应该将 =>
看作具有通用量化的逻辑蕴涵:
所有类型
a
和b
,
如果
a
是集成
和b $ c的实例$ c>是
Num
,
然后
fromInteral
可以使用a
并生成b
。
此函数将类型
a
(它是Integral 类型)到
b
类型(它是更一般的Num
类的一个实例)。例如。你不能将整数1
添加到Haskell中的float2
,而无需转换前者:Prelude> (1 :: Int)+(2 :: Float)
< interactive>:10:15:
无法与实际类型为'Float'的预期类型'Int'匹配b $ b在`(+)'的第二个参数中,即`(2 :: Float)'
在表达式中:(1 :: Int)+(2 :: Float)
在等式:it =(1 :: Int)+(2 :: Float)
Prelude> fromIntegral(1 :: Int)+(2 :: Float)
3.0
LYAH describes
fromIntegral
as:From its type signature we see that it takes an integral number and turns it into a more general number. That's useful when you want integral and floating point types to work together nicely.
I don't understand how this function works at all or why it is needed from playing around with the interpreter.
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?
解决方案fromIntegral :: (Integral a, Num b) => a -> b
takes one arg. The
=>
should be read as a logical implication with universal quantification:for all types
a
andb
,if
a
is an instance ofIntegral
andb
is an instance ofNum
,then
fromIntegral
can take ana
and produce ab
.
This function converts a value of type
a
(which is anIntegral
type) to theb
type (which is an instance of the more generalNum
class). E.g. you cannot add the integer1
to the float2
in Haskell without converting the former: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
这篇关于我不明白:来自整合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!