[Haskell-beginners] Some confusion still with a YAHT example
David Schonberger
llp_yyz at hotmail.com
Wed Jan 7 19:31:04 EST 2009
Hello all. This is my first post and I'm essentially a rank beginner with Haskell, having used it briefly some 7 years ago. Glad to be back but struggling with syntax and understanding error messages.
This post actually ties to a prior post, http://www.haskell.org/pipermail/beginners/2008-December/000583.html
My troubles are with exercise 3.10, p45 of from HDIII's "Yet Another Haskell Tutorial" (YAHT). The exercise states:
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 whereimport 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090107/525c4d9a/attachment.htm
More information about the Beginners
mailing list