haskellghc

Convert Num to Double in Haskell


I know about the existence of fromRational, fromInteger and fromIntegral.
But is there a more generic function to convert any Num to the Double type?
I'm also aware of the fact that Num is a set of types, and possibly that comes with limitations of how to use it.
But it is possible?
Something like:

fromNum::(Num a) => a -> Double

And preferably, without installing any additional packages.


Solution

  • There is absolutely not a way to do this, and for a very good reason. Num is a generic type designed to be used for anything vaguely "addable" and "multiply-able". You can very loosely think of it as a ring[1]. This means that things like vectors, points, and matrices are Num. And there's no reasonable, canonical way to convert a Matrix a into a Double.

    You've already noted that there are several ways to get to Double from more specific typeclasses like Integral.


    [1] Yes, fromInteger is also on Num. That's largely considered a misfeature and libraries doing things with matrices usually just provide an awkward default implementation.