Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sqrt from Int in Haskell

How can I get sqrt from Int.

I try so:

sqrt . fromInteger x 

But get error with types compatibility.

like image 320
0xAX Avatar asked Jul 14 '11 14:07

0xAX


People also ask

How do you find the square root in Haskell?

fromIntegral :: (Integral a, Num b) => a -> b takes your Int (which is an instance of Integral ) and "makes" it a Num . sqrt :: (Floating a) => a -> a expects a Floating , and Floating inherit from Fractional , which inherits from Num , so you can safely pass to sqrt the result of fromIntegral.

What is AUX in Haskell?

There is no keyword aux , my guess is this is just the name they used for a local function. Just like you can define top-level values: myValue = 4. or top-level functions: myFunction x = 2 * x.

Is Haskell an integer?

Haskell has two integral types, namely Int and Integer . Int is the type of limited-precision integers; this means that there is a smallest integer of type Int , namely minBound , and a greatest integer of type Int , namely maxBound .

What does NUM mean in Haskell?

Num is a typeclass — a group of types — which includes all types which are regarded as numbers. The (Num a) => part of the signature restricts a to number types – or, in Haskell terminology, instances of Num .


1 Answers

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.)

like image 112
augustss Avatar answered Sep 18 '22 17:09

augustss