user1131532
user1131532

Reputation: 65

How do I convert a -> Float?

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.

Upvotes: 5

Views: 5379

Answers (3)

ehird
ehird

Reputation: 40787

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.

Upvotes: 11

dflemstr
dflemstr

Reputation: 26157

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.

Upvotes: 1

penelope
penelope

Reputation: 8419

Did you try with fromIntegral function?

fromIntegral :: (Integral a, Num b) => a -> b

I've just tested it in ghci, and while the following code does not work (wrong types):

> let a = 1::Int
> let b = 1::Float
> a + b
Couldn't match expected type `Int' against inferred type `Float'....

If you use fromIntegral, it works just fine:

> let a = 1::Int
> let b = 1::Float
> (fromIntegral a) + b
2.0

Upvotes: 0

Related Questions