Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overuse of fromIntegral in Haskell

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

like image 989
Ash Avatar asked Aug 10 '10 21:08

Ash


2 Answers

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.

like image 175
luqui Avatar answered Oct 03 '22 13:10

luqui


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.

like image 43
sepp2k Avatar answered Oct 03 '22 14:10

sepp2k