Paul Carey
Paul Carey

Reputation: 1798

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?

Upvotes: 36

Views: 49697

Answers (1)

bheklilr
bheklilr

Reputation: 54058

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

Upvotes: 41

Related Questions