在Haskell中从Int获取sqrt [英] Get sqrt from Int in Haskell
问题描述
如何从 Int
获取 sqrt
。
我这样做:
sqrt。 fromInteger x
但是获得类型兼容性的错误。
fromIntegral
: 前奏>让x = 5 :: Int
Prelude> sqrt(fromIntegral x)
2.23606797749979
均 Int
和 Integer
是 Integral
的实例:
-
fromIntegral ::(Integral a,Num b)=> a - > b 将你的
Int
(它是Integral
的一个实例)并且制作它Num
。 -
sqrt ::(Floating a)=> a - >一个
需要一个浮动
,并且浮动
从小数
,它继承自Num
,因此您可以安全地传递给sqrt
< c $ c> fromIntegral
我认为类 diagram Haskell Wikibook 在这种情况下非常有用。
How can I get sqrt
from Int
.
I try so:
sqrt . fromInteger x
But get error with types compatibility.
Using fromIntegral
:
Prelude> let x = 5::Int
Prelude> sqrt (fromIntegral x)
2.23606797749979
both Int
and Integer
are instances of Integral
:
fromIntegral :: (Integral a, Num b) => a -> b
takes yourInt
(which is an instance ofIntegral
) and "makes" it aNum
.sqrt :: (Floating a) => a -> a
expects aFloating
, andFloating
inherit fromFractional
, which inherits fromNum
, so you can safely pass tosqrt
the result offromIntegral
I think that the classes diagram in Haskell Wikibook is quite useful in this cases.
这篇关于在Haskell中从Int获取sqrt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!