简体   繁体   中英

How to convert (Num a) => a to Float in Haskell?

Is it possible to combine the following two functions into one polymorphic function in Haskell?

mutiplyByTwoI :: Int -> Float
mutiplyByTwoI x = fromIntegral x * 2.0

mutiplyByTwoF :: Float -> Float
mutiplyByTwoF x = x * 2.0

I tried Num a , but I couldn't find a way to convert Num a to Float.

mutiplyByTwo :: (Num a) => a -> Float
mutiplyByTwo = undefined

Not every instance of Num has a sensible conversion to Float . For a simple (ha ha) example consider complex numbers:

-- represented in rectangular coordinates
data Complex = Complex { real :: Float, imaginary :: Float } deriving (Eq, Ord, Show, Read)

instance Num Complex where
    Complex u v + Complex x y = Complex (u + x) (v + y)
    Complex u v * Complex x y = Complex (u * x - v * y) (v * x + u * y)
    negate (Complex u v) = Complex (negate u) (negate v)
    -- etc

Clearly there is no way to convert a Complex to a Float without throwing away information: Float s live on (a subset of) the real line whereas complex numbers live on the complex plane. There is no function toFloat :: Num a => a -> Float that works for all instances of Num .

You can write

byTwo :: Real a => a -> Float
byTwo x = 2 * realToFrac x

which can be specialized to both types you request, Int -> Float and Float -> Float .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM