Get sqrt from Int in Haskell
Remember, application binds more tightly than any other operator. That includes composition. What you want is
sqrt $ fromIntegral x
Then
fromIntegral x
will be evaluated first, because implicit application (space) binds more tightly than explicit application ($).
Alternately, if you want to see how composition would work:
(sqrt . fromIntegral) x
Parentheses make sure that the composition operator is evaluated first, and then the resulting function is the left side of the application.
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.
Perhaps you want the result to be an Int
as well?
isqrt :: Int -> Int
isqrt = floor . sqrt . fromIntegral
You may want to replace floor
with ceiling
or round
.
(BTW, this function has a more general type than the one I gave.)