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?
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.
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'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.
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
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