[Haskell-beginners] Sequential IO processing
Sergey V. Mikhanov
sergey at mikhanov.com
Thu Feb 19 09:56:02 EST 2009
Hi community,
I am making my first steps in Haskell, reading Haskell wikibook and
now stuck with one of the excercises, namely this one:
Implement a function sequenceIO :: [IO a] -> IO [a]. Given a list of
actions, this function runs each of the actions in order and returns
all their results as a list.
This is what I came with:
ioOne :: Num a => IO a
ioOne = do print guid
return guid
where
guid = 2
ioTwo :: Num a => IO a
ioTwo = do print guid
return guid
where
guid = 3
sequenceIO :: Num a => [IO a] -> IO [a]
sequenceIO [] = return []
sequenceIO (x : xs) = do result <- x
return result : sequenceIO xs
First two functions are there because of the invocation that I've
planned: sequenceIO [getGuid, getNextGuid].
However, this could not be compiled (GHC):
Couldn't match expected type `[m a]' against inferred type `IO [a]'
In the second argument of `(:)', namely `sequenceIO xs'
In the expression: return result : sequenceIO xs
In the expression:
do result <- x
return result : sequenceIO xs
Fine, I thought, something wrong with the type of the 'sequenceIO xs'
(becasue I am sure the type of 'result' is fine). So I wrote another
program to check what happens to the result of IO action evaluation
(namely, which type is assigned):
bar :: Num a => IO a
bar = do print guid
return guid
where
guid = 2
foo = do result <- bar
result
This could not be compiled either:
No instance for (Num (IO b))
arising from a use of `bar' at auxil.hs:8:19-21
Possible fix: add an instance declaration for (Num (IO b))
In a stmt of a 'do' expression: result <- bar
In the expression:
do result <- bar
result
In the definition of `foo':
foo = do result <- bar
result
I am a newbie, so I am interpreting this like "Haskell could not
construct Num from the result of invocation of bar, which is of type
IO a". But why do I need this at all? When doing console I/O with
'result <- getLine', I do not need to reconstruct String from the
result.
What am I doing wrong? Where is the failure in reasoning?
Thanks,
Sergey
More information about the Beginners
mailing list