Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does type casting work in Haskell?

I want to be able to be able to truncate a float or double in a similar way you would in Java: (int)5.583, for example.

I've done some research and, to my knowledge, there's nothing imported in Prelude for this. So I'm wondering how I would construct a function that does it. I thought maybe if I did show 5.583 and then took a substring up to the decimal point and then converted that to an Int, but that seems like it would be terribly inefficient when using only recursion. So is there a more simple way to go about it?

like image 581
Eben Cowley Avatar asked Jan 05 '23 08:01

Eben Cowley


2 Answers

I want to be able to be able to truncate float or double

Delightfully, the function that truncates fractionals to integrals is named "truncate".

https://www.stackage.org/haddock/lts-8.4/base-4.9.1.0/Prelude.html#v:truncate

λ> truncate 5.583
5

Its type is

truncate :: (Real a, Fractional a, Integral b) => a -> b

This is just an ordinary function. Haskell does not have any language feature (or kludge, if you will) akin to type casting in Java.

like image 128
Chris Martin Avatar answered Jan 06 '23 23:01

Chris Martin


Converting floating point numbers with ghc is possible with:

λ> :m GHC.Float
λ> :t float2Double
float2Double :: Float -> Double
λ> :t double2Float
double2Float :: Double -> Float
λ> :t double2Int
double2Int :: Double -> Int
λ> :t float2Int
float2Int :: Float -> Int
λ> :t int2Double
int2Double :: Int -> Double
λ> :t int2Float
int2Float :: Int -> Float

But for floating point numbers to ints I'd recommend using ceiling, round and floor, and fromIntegral for backwads conversion.

Edit: after reading the question more carefully, @Chris Martin's answer is the correct one:

λ> :t truncate
truncate :: (Integral b, RealFrac a) => a -> b
like image 32
lehins Avatar answered Jan 06 '23 22:01

lehins