Write a program that will repeatedly ask the user for numbers until she
types in zero, at which point it will tell her the sum of all the numbers, the product of
all the numbers, and, for each number, its factorial. For instance, a session might look
like:
Note that the sample session accompanying the exercise suggests a session such as:
Give me a number (or 0 to stop):
5
Give me a number (or 0 to stop):
8
Give me a number (or 0 to stop):
2
Give me a number (or 0 to stop):
0
The sum is 15
The product is 80
5 factorial is 120
8 factorial is 40320
2 factorial is 2
The following code handles the sum and products pieces--I built the module incrementally--but fails on the factorial part. In fact my current code, if it worked, would only output something like:
The sum is 15
The product is 80
120
40320
2
But I'm not even getting that much. Here's the code:
--begin code
module AskForNumbers
where
import IO
askForNums = do
putStrLn "Enter a pos int or 0 to end: "
numStr <- getLine
let num = read numStr
if num == 0
then return []
else do
rest <- askForNums
return (num:rest)
listFactorial l =
if length l == 0
then return 1
else do
fact (head l)
listFactorial (tail l)
fact n =
if n == 0
then return 1
else return foldr (*) 1 [1..n]
f = do
nums <- askForNums
putStr ("Sum is " ++ (show (foldr (+) 0 nums)) ++ "\n")
putStr ("Product is " ++ (show (foldr (*) 1 nums)) ++ "\n")
listFactorial nums
--end code
Here is the error msg I get when I load into WinHugs (Sept 2006 version):
ERROR file:.\AskForNumbers.hs:22 - Ambiguous type signature in inferred type
*** ambiguous type : (Num a, Num [a], Monad ((->) [b]), Num c, Num (b -> [a] -> [a]), Enum a, Monad ((->) (c -> c -> c))) => a -> [b] -> [a]
*** assigned to : fact
Ambiguous type assigned to fact. Ok. Not sure what to make of that or how to correct it. I though I was passing fact an Integer, since I think nums is a list of Integers, since the sum and product lines in f work ok.
Help? Thanks.
David