Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a -> Float?

Tags:

haskell

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.

like image 869
user1131532 Avatar asked Jan 08 '12 10:01

user1131532


People also ask

How do you change a decimal to a float?

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.

How do you convert float to fixed?

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.

How do you convert a value to a float in Python?

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.


2 Answers

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.

like image 189
ehird Avatar answered Nov 15 '22 10:11

ehird


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.

like image 29
dflemstr Avatar answered Nov 15 '22 09:11

dflemstr