Iter Ator
Iter Ator

Reputation: 9269

How to convert any Num value to a Floating value in Haskell?

I would like to use functions (for example exponential functions), which only works on Floating types. My input can be any type of Num: Integer, Float, Fractional ...

How is it possible to convert all of them to a Floating?

numToFloating :: (Num a, Floating b) => a -> b
...

I have no idea, where to start

Upvotes: 1

Views: 65

Answers (1)

luqui
luqui

Reputation: 60463

You cannot. The following is a valid specialization

numToFloating :: Complex Float -> Float

since ComplexFloat is an instance of Num. What are we supposed to do with the imaginary part?

So what you really want to say is that the input is any Real type, giving the signature

:: (Real a, Floating b) => a -> b

which turns out to be a little stronger than necessary. There is already realToFrac

realToFrac :: (Real a, Fractional b) => a -> b

which will do what you need, since any Floating type is already Fractional.

Upvotes: 3

Related Questions