Get sqrt from Int in Haskell

48,474

Solution 1

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

I think that the classes diagram in Haskell Wikibook is quite useful in this cases.

Solution 2

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

Solution 3

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.

Share:
48,474
0xAX
Author by

0xAX

I'm a software engineer with a particular interest in the Linux, git, low-level programming and programming in general. Now I'm working as Erlang and Elixir developer at Travelping. Writing blog about erlang, elixir and low-level programming for x86_64. Author of the Linux Insides book. My linkedin profile. Twitter: @0xAX Github: @0xAX

Updated on January 08, 2021

Comments

  • 0xAX
    0xAX over 3 years

    How can I get sqrt from Int.

    I try so:

    sqrt . fromInteger x
    

    But get error with types compatibility.