I think that I could use fromEnum for a -> Int but how do I do it for a -> Float. I need my variable to be a Float for my function to work but I can't work out how to convert it? I've gone through the Prelude and can't see anything that would work. Sorry if this is a really stupid question but I'm just starting out.
To convert a decimal number to binary floating point representation: Convert the absolute value of the decimal number to a binary integer plus a binary fraction. Normalize the number in binary scientific notation to obtain m and e. Set s=0 for a positive number and s=1 for a negative number.
To convert the internal value of a fixed-point number to floating point, simply divide by the scaling factor. To convert the other way, multiply by the scaling factor and round to the nearest integer.
We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.
It depends on what a is. If a is an instance of Integral, like Int
or Integer
, you can use
fromIntegral :: (Integral a, Num b) => a -> b
If a is an instance of Real, like Rational or Double, you can use
realToFrac :: (Real a, Fractional b) => a -> b
There are also special functions for Integer and Rational that fromIntegral
and realToFrac
are based on:
fromInteger :: (Num a) => Integer -> a
fromRational :: (Fractional a) => Rational -> a
If a is an instance of Enum (and so you can use fromEnum
, as you said), then fromIntegral . fromEnum
should do it. fromEnum
converts a to Int
, then fromIntegral
converts from Int
to Float
, so fromIntegral . fromEnum
converts a to Float
.
You can convert an (Enum a) => a
to an Int
first, and then the Int
to a Float
. To convert an Int
to a Float
(or many other number types), you use fromIntegral
. A function that combines these two functions would be:
floatFromEnum :: (Enum a) => a -> Float
floatFromEnum = fromIntegral . fromEnum
EDIT: Note that fromEnum
doesn't work for any a
, as you are implying, but only works for a
's that are Enum
instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With