Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Integer to Double in Haskell

I want to compound growth over a year but I don't care about decimal points, so I tried

take 52 $ iterate (floor . (*1.1)) 100 

The problem is that the type of (floor . (*1.1)) is Double -> Integer, whereas the type expected by the first arg of iterate is a -> a.

I tried a couple of approaches, but ended up tying myself in knots.

What is the preferred solution to keeping numeric types consistent across function application?

like image 960
Paul Carey Avatar asked Aug 16 '13 19:08

Paul Carey


People also ask

What does fromIntegral do in 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.

What is double in Haskell?

Double is the double-precision floating point type, a good choice for real numbers in the vast majority of cases. (Haskell also has Float , the single-precision counterpart of Double , which is usually less attractive due to further loss of precision.)

What is the difference between int and Integer in Haskell?

What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range.


1 Answers

The usual way to convert an Int to a Double is to use fromIntegral, which has the type (Integral a, Num b) => a -> b. This means that it converts an Integral type (Int and Integer) to any numeric type b, of which Double is an instance.

Your case sounds like you want to convert a Double to an Int, which I would recommend floor for, but you'll have to make sure that your input is a Double. For this, you can use the fromIntegral function with

take 52 $ iterate (floor . (* 1.1) . fromIntegral) 100 

However, this will give you inaccurate results, since you are truncating at each step. I would suggest doing

take 52 $ map floor $ iterate (* 1.1) $ fromIntegral 100 
like image 190
bheklilr Avatar answered Sep 18 '22 14:09

bheklilr