How to convert a & # 8594; Float?

I think I could use fromEnum for a β†’ Int, but how to do it for a β†’ Float. I need my variable for Float for my function, but I can’t decide how to convert it? I went through the Prelude and do not see anything that would work. Sorry if this is a really stupid question, but I'm just getting started.

+4
source share
3 answers

It depends on what you have. If a is an Integral instance like Int or Integer , you can use

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

If a is an instance of Real, such as Rational or Double, you can use

 realToFrac :: (Real a, Fractional b) => a -> b 

There are also special functions for Integer and Rational, which fromIntegral and realToFrac are based on:

 fromInteger :: (Num a) => Integer -> a fromRational :: (Fractional a) => Rational -> a 

If a is an instance of Enum (and therefore you can use fromEnum , as you said), then fromIntegral . fromEnum fromIntegral . fromEnum has to do this. fromEnum converts a to Int , then fromIntegral converts from Int to Float , so fromIntegral . fromEnum fromIntegral . fromEnum converts a to Float .

+8
source

First you can convert (Enum a) => a to Int , and then Int to Float . To convert Int to Float (or many other types of numbers), you use fromIntegral . The function that combines these two functions will be:

 floatFromEnum :: (Enum a) => a -> Float floatFromEnum = fromIntegral . fromEnum 

EDIT: Note that fromEnum does not work for any a , as you mean, but only works for a , which are Enum instances.

+1
source

Have you tried using the fromIntegral function?

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

I just tested it in ghci and while the following code is not working (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 fine:

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

Source: https://habr.com/ru/post/1389887/


All Articles