I wonder if there is a function that converts rational types to Float (Rational a => a -> Float).
I tried hoogling, but found nothing.
In Haskell, we can convert Int to Float using the function fromIntegral .
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.
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.
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.
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
There is also fromIntegral to convert Int
s and Integer
s to any instance of Num
.
foo :: Float -> Float
foo x = x+1
value :: Int
value = 4
newValue = foo (fromIntegral value)
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