Reputation:
I have the following function in Haskell:
invertedSum :: Integer -> Integer
invertedSum n = n + (read . reverse . show) n
I need to know the number of sums that must be made in order for the number to be capicua. That is to say,
invertedSum 1999 = 11990 (1999+9991)
invertedSum 11990 = 21901
invertedSum 21901 = 32813
invertedSum 32813 = 64636
invertedSum 64636 = 128282
invertedSum 128282 = 411103
invertedSum 411103 = 712217
isCapicua :: Integer -> Bool
isCapicua n | show n == (reverse . show) n = True
| otherwise = False
isCapicua 712217 == True
So, I want to generate the following list, but I don't know how.
sumUpToCapicua 1999 = [11990, 21901, 32813, 64636, 128282, 411103, 712217]
genericLength (sumUpToCapicua 1000000079994144385) == 259
Upvotes: 0
Views: 312
Reputation: 233267
You already have a function invertedSum
with the type Integer -> Integer
. If I understand the question correctly, you'd like to apply it multiple times, starting with a particular Integer
(e.g. 1999
).
You could use iterate
for that purpose. It has the type:
Prelude> :t iterate
iterate :: (a -> a) -> a -> [a]
In other words, it'll take any function a -> a
, as well as an initial value a
, and produce an infinite list of a
values.
In your case, invertedSum
has the type Integer -> Integer
, and the initial value you'd like to use (e.g. 1999
) would also be of the type Integer
, so it all fits: a
would be Integer
.
Try using invertedSum
and e.g. 1999
with iterate
. Be aware that this produces an infinite list, so if you experiment with this in GHCi, you probably want to use e.g. take 10
to cap the number of values generated.
Upvotes: 2