[Haskell-beginners] Problems when trying to solve yaht exercise 3.10

Andrew Wagner wagner.andrew at gmail.com
Fri Mar 20 08:57:14 EDT 2009


Ah, you came very close to getting this right. The problem is on your two
putStrLn lines. For example, putStrLn "The sum is " ++ show(sum)
This parses as (putStrLn "The sum is ") ++ show(sum). Thus, it's trying to
use ++ on an IO () and a string. This obviously won't work. You need one of
the following:

putStrLn ("The sum is " ++ show(sum))
putStrLn $ "The sum is " ++ show(sum)

Ditto for the product line. Also, if I can make 2 other quick comments:
product and sum are already defined in the prelude, so there's no need to
define them here. You should also get used to putting type signatures on
your functions, because it's a good practice. Otherwise, good job!

2009/3/20 ZelluX <zellux at gmail.com>

> Hi, all
>
> I'm new to haskell and currently reading yaht. I find some problems when
> trying to solve exercise 3.10.
>
> The exersices asks to read a list of numbers terminated by a zero, and
> figure out the sum and product of the list. My program is as follows:
>
> ex3_10 = do
>   hSetBuffering stdin LineBuffering
>   numbers <- getNumber
>   let sum = foldr (+) 0 numbers
>       product = foldr (*) 1 numbers
>   putStrLn "The sum is " ++ show(sum)
>   putStrLn "The product is " ++ show(product)
>
> getNumber = do
>   putStrLn "Give me a number (or 0 to stop):"
>   num <- getLine
>   if read num == 0
>      then return []
>      else do
>        rest <- getNumber
>        return (read num : rest)
>
> But when i load the program, ghci reports error:
>     Couldn't match expected type `[a]' against inferred type `IO ()'
>     In the first argument of `(++)', namely `putStrLn "The sum is "'
>     In a stmt of a 'do' expression:
>           putStrLn "The sum is " ++ show (sum)
>
> And i just don't understand the first sentence. Could you tell what does it
> mean?
>
> Thanks for your reply
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20090320/97683cc6/attachment.htm


More information about the Beginners mailing list