[Haskell-cafe] Way to implement toFloat :: (Num a) => a -> Float

Evan Laforge qdunkan at gmail.com
Thu Dec 12 20:32:41 UTC 2013


Just be careful, realToFrac goes through rational first, which can't
represent special values like NaN and Infinity, so those will turn
into random numbers.  Also it can be very inefficient.

Still, it's acceptable for a generic "any to Float" conversion.  For
conversion between Doubles and Floats (or newtypes thereof), however,
I use things like

d2f :: Double -> Float
d2f (Types.D# d) = Types.F# (Prim.double2Float# d)

On Thu, Dec 12, 2013 at 11:55 AM, EatsKittens
<temporalabstraction at gmail.com> wrote:
> Ah, I had no ideal the real typeclass existed, that completely solves my
> issue.
>
>
> On 12 December 2013 20:39, Ben Gamari <bgamari.foss at gmail.com> wrote:
>>
>> EatsKittens <temporalabstraction at gmail.com> writes:
>>
>> > Is there a way to add a method to a typeclass like num to implement this
>> > concept? A function that converts any number to floats?
>> >
>> Does the following do what you expect?
>>
>> realToFrac :: (Fractional b, Real a) => a -> b
>>
>> realToFrac' :: (Real a) => a -> Float
>> realToFrac' = realToFrac :: (Real a) => a -> Float
>>
>> Cheers,
>>
>> - Ben
>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list