34

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?

2
  • 4
    You can't keep rounding intermediate results and hope to get a correct answer at the end. Why not move the floor out of the iterate and do map floor . take 52 $ ... ?
    – Fixnum
    Aug 16, 2013 at 19:41
  • @Fixnum fair point, it was just something I tried to run in ghci when I ran into the issue.
    – Paul Carey
    Aug 16, 2013 at 19:46

1 Answer 1

40

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
2
  • I will also add that the latter expression will be slightly faster since fromIntegral is performed once, (* 1.1) is still repeated, and floor is performed only as many times as necessary, although an argument could be made to transpose map floor and take 52.
    – bheklilr
    Aug 16, 2013 at 19:53
  • 3
    Equivalently written as: take 52 . map floor . iterate (* 1.1) . fromIntegral $ 100
    – Davorak
    Aug 16, 2013 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.