Haskell – Converting Num to Float

haskelltype conversion

I need to be able to convert generic numbers (instances of Num) to a Float. I searched Hoogle for a function with the signature Num n => n -> Float, but I couldn't find any such functions (although it may be possible to compose it). I also looked over the Num typeclass, and it doesn't seem to require instances of it to supply any conversion functions that may help me.

Why do I need to do this? I created a typeclass Moveable that defines operations to move a coordinate, and allowed it to work with any instance of Num, since the only thing required to move a coordinate is +, which is defined by Num. My end goal was to use this with Gloss (a graphics library), but unfortunately, Gloss only uses Floats. That means that if I'm storing the coordinate as a Num, I'll eventually need to convert it when I try to display an object.

I'd rather not make the number type more specific to so it'll work with Gloss. Does anyone have any ideas that could help?

Best Answer

Why are you "storing" your values as Num instead of Float? (How are you storing them? Num isn't even a type so you can't be storing them as that...)

Prelude> let y = 3.0::Float
Prelude> :t y
y :: Float
Prelude> let plus a b = a+b
Prelude> :t plus
plus :: Num a => a -> a -> a
Prelude> :t (plus y)
(plus y) :: Float -> Float
Prelude> plus y y
6.0
Prelude>

In conclusion: Just use Float. Unless you have some reason not to?


As a rule, just remember that Haskell has very little in the way of conversions made available even though you can force them in a variety of ways if it's really necessary. The idiomatic approach to these things is always:

Figure out how to make the type information available to the compiler so your types are gauranteed and you won't need to do conversions

Related Topic