Reputation: 197
I have the following function that will recursively multiply the digits of a number until it reaches a single digit number
multResWithCounter' :: (Int, [Int],[Integer]) -> (Int, [Int],[Integer])
multResWithCounter' (counter, listOfDigits,listOfProducts)
| (length listOfDigits) <= 1 = (counter, listOfDigits, listOfProducts)
| otherwise = multResWithCounter' ((counter + 1), newListOfDigits, digitProduct:listOfProducts)
where newListOfDigits = map (\n -> read [n] :: Int) (show $ digitProduct)
digitProduct = ((product listOfDigits) :: Integer)
Which of course doesn't compile in ghci, complaining that it couldn't match expected type Integer with actual type Int. If I back down and change the type declaration to Int and call it, this way for example,
multResWithCounter' (0,[2,7,7,7,7,7,7,8,8,8,8,8,8,9,9],[])
I get
(2,[0],[0,1191706624])
Now this "1191706624" is of course the result of
(product [2,7,7,7,7,7,7,8,8,8,8,8,8,9,9]) `mod` (maxBound :: Int)
and sure enough the result of the first part when run directly in ghci is the correct 4996238671872.
So, how can I have Haskell give me Integer product results (that I will turn to strings right away with show anyway)?
Thanks
Upvotes: 0
Views: 476
Reputation: 152707
You may use
fromIntegral :: Int -> Integer
to promote an Int
to an Integer
. For similar future questions, you can use Hoogle to search for functions by type, which would have gotten you a closely related answer:
toInteger :: Int -> Integer
Upvotes: 5