Whenever I write a function using doubles and integers, I find this problem where I am constantly having to use 'fromIntegral' everywhere in my function. For example:
import Data.List roundDouble :: Double -> Int -> Double roundDouble x acc = fromIntegral (round $ x * 10 ** fromIntegral acc) / 10 ** fromIntegral acc
Is there an easier way of writing this? (I know there may be easier ways of rounding a number and if there are please let me know! However I am mainly interested in how to avoid using so many 'fromIntegrals'.)
Thanks, Ash
Sometimes I find a helper function useful:
roundDouble x acc = (round $ x * 10 ^ acc) /. (10 ^ acc) where x /. y = fromIntegral x / fromIntegral y
That helper function can also be written:
(/.) = (/) `on` fromIntegral
Where on
is from Data.Function
.
You can use ^
instead of **
. ^
takes any Integral as it's second argument, so you don't need to call fromIntegral
on the second operand. So your code becomes:
roundDouble x acc = fromIntegral (round $ x * 10 ^ acc) / 10 ^ acc
Which has only one fromIntegral
. And that one you can't get rid off as round
naturally returns an Integral and you can't perform non-integer division on an Integral.
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