Get sqrt from Int in Haskell

前端 未结 3 1822
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 04:07

How can I get sqrt from Int.

I try so:

sqrt . fromInteger x

But get error with types compatibility.

3条回答
  •  死守一世寂寞
    2020-12-15 04:42

    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.

提交回复
热议问题