Newbie question

Dmitri Pissarenko mailing-lists at dapissarenko.com
Sun Jan 9 07:18:15 EST 2005


Hello!

I am learning Haskell according to the "Yet Another Haskell Tutorial" by Hal
Daume Ill.

One of the exercises involves

a) asking the user to enter several numbers (while the end of the sequence is
indicated by entering 0)
b) calculate the sum of those numbers.

The program given below tries to do that.

I can read a list of strings. Then, I try to convert the list of strings into
a list of numbers by means of map.

That is, given a list ["1","2","3"], I want to convert it into [1,2,3].

In GHCi, this is done via

map read ["1","2","3"]

However, when I apply this same call in my program below, I'm getting
following error when loading the program in GHCi:

<error-message>
Loading package base ... linking ... done.
Compiling Main             ( AskForNumbers.hs, interpreted )

AskForNumbers.hs:10:
    Couldn't match `IO' against `[]'
        Expected type: IO t
        Inferred type: [b]
    In the application `map read words'
    In a 'do' expression: map read words
Failed, modules loaded: none.
</error-message>

Line 10 corresponds to the statement

map read words,

which seems to work in GHCi.

What am I doing wrongly?

Thanks in advance

Dmitri Pissarenko

PS: What follows is my Haskell program.

module Main
	where

import IO

main = do
	hSetBuffering stdin LineBuffering
	words <- askForNumbers
	printWords words
	map read words
	putStrLn "The sum is"
	foldl (+) 0 words

askForNumbers = do
	putStrLn "Please enter a number:"
	text <- getLine
	if text == ""
		then return []
		else if text == "0"
			then
				return []
			else do
				rest <- askForNumbers
				return (text : rest)

printWords [] = putStrLn "EOL"
printWords (h : t) = do
	putStrLn h
	printWords t


More information about the Glasgow-haskell-users mailing list