Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No toFloat in Haskell

Tags:

haskell

I wonder if there is a function that converts rational types to Float (Rational a => a -> Float).

I tried hoogling, but found nothing.

like image 263
aelguindy Avatar asked Dec 21 '11 10:12

aelguindy


People also ask

How to turn a Int into float in Haskell?

In Haskell, we can convert Int to Float using the function fromIntegral .

What does fromIntegral do Haskell?

The workhorse for converting from integral types is fromIntegral , which will convert from any Integral type into any Num eric type (which includes Int , Integer , Rational , and Double ): fromIntegral :: (Num b, Integral a) => a -> b.

How do you find the square root in Haskell?

fromIntegral :: (Integral a, Num b) => a -> b takes your Int (which is an instance of Integral ) and "makes" it a Num . sqrt :: (Floating a) => a -> a expects a Floating , and Floating inherit from Fractional , which inherits from Num , so you can safely pass to sqrt the result of fromIntegral.

How do you do division in Haskell?

The (/) function requires arguments whose type is in the class Fractional, and performs standard division. The div function requires arguments whose type is in the class Integral, and performs integer division. More precisely, div and mod round toward negative infinity.


2 Answers

In Haskell you don't convert to but from. See fromRational.

threeHalves :: Ratio Integer
threeHalves = 3 % 2
sqrt threeHalves -- Fails
sqrt $ fromRational threeHalves -- Succeeds

If you need a Rational -> Float function, you can define it as

toFloat x = fromRational x :: Float
like image 197
Jan Avatar answered Oct 10 '22 16:10

Jan


There is also fromIntegral to convert Ints and Integers to any instance of Num.

foo :: Float -> Float
foo x = x+1

value :: Int
value = 4

newValue = foo (fromIntegral value)
like image 33
is7s Avatar answered Oct 10 '22 17:10

is7s